不同于UDP,TCP首先要用一个欢迎套接字,握手成功后创建一个新的传输套接字

客户端

  1. """
  2. TCP Socket的客户端
  3. 环境 python3
  4. """
  5. from socket import *
  6. serverName = '180.201.20.208'
  7. serverPort = 12000
  8. clientSocket = socket(AF_INET, SOCK_STREAM)
  9. clientSocket.connect((serverName, serverPort))
  10. # python3 改动
  11. sentence = input("Input lowercase sentence:")
  12. # python3 改动 socket要求byte类型数据
  13. clientSocket.send(sentence.encode())
  14. modifiedSentence = clientSocket.recv(1024)
  15. # python3 改动
  16. print("From Server:" + modifiedSentence.decode())
  17. clientSocket.close()

服务器端

  1. """
  2. TCP Socket的服务器端
  3. 环境 python3
  4. """
  5. from socket import *
  6. serverPort = 12000
  7. serverSocket = socket(AF_INET, SOCK_STREAM)
  8. serverSocket.bind(("", serverPort))
  9. serverSocket.listen(1)
  10. # python3 改动
  11. print("The server is ready to receive")
  12. while 1:
  13. connectSocket , addr = serverSocket.accept()
  14. sentence = connectSocket.recv(1024)
  15. capitalizeSentence =sentence.upper()
  16. connectSocket.send(capitalizeSentence)
  17. connectSocket.close()

实验结果

输入小写字符串,能够返回大写字符串
image.png