UDP

  1. # UDP客户端
  2. from socket import *
  3. serverName = "hostname"
  4. serverPort = 12000 #服务器端口
  5. clientSocket = socket(AF_INET, SOCK_DGRAM) #AF_NET:IPv4,SOCK_DGRAM:UDP类型
  6. message = raw_input("Input fucking message")
  7. clientSocket.sendto(message,(serverName, serverPort))
  8. recMsg, svrAddr = clientSocket.recvfrom(2048) #缓存长度
  9. print recMsg
  10. clientSocket.close()
  11. #UDP服务端
  12. from socket import *
  13. svrPort = 12000
  14. svrSocket = socket(AF_INET, SOCK_DGRAM)
  15. svrSocket.bind(('', svrPort))
  16. print 'waiting for message...'
  17. while True:
  18. msg, clientAddr = svrSocket.recvfrom(2048)
  19. msgModified = msg.upper()
  20. svrSocket.sendto(msgModified, clientAddr)

TCP

  1. #TCPClient.py
  2. from socket import *
  3. svrName = 'hostname'
  4. svrPort = 12000
  5. clientSocket = sockent(AF_INET, SOCK_STREAM) #SOCK_STREAM:TCP类型套接字
  6. clientSocket.connect((serverName, serverPort))
  7. sentence = raw_input('Input lowercase sentence:')
  8. clientSocket.send(sentence)
  9. modifiedSentence = clientSocket.recv(1024)
  10. print 'From Server:', modifiedSentence
  11. clientSocket.close()
  12. #TCPServer.py
  13. from socket import *
  14. svrPort = 12000
  15. svrSocket = socket(AF_INET,SOCK_STREAM)
  16. svrSocket.bind(('', svrPort))
  17. svrSocket.listen(1) #请求连接的最大数
  18. while 1:
  19. connection, addr = svrSocket.accept()
  20. sentence = connection.recv(1024)
  21. modifiedSentence = sentence.upper()
  22. connection.send(modifiedSentence)
  23. connection.close()