不同于UDP,TCP首先要用一个欢迎套接字,握手成功后创建一个新的传输套接字
客户端
"""
TCP Socket的客户端
环境 python3
"""
from socket import *
serverName = '180.201.20.208'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
# python3 改动
sentence = input("Input lowercase sentence:")
# python3 改动 socket要求byte类型数据
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
# python3 改动
print("From Server:" + modifiedSentence.decode())
clientSocket.close()
服务器端
"""
TCP Socket的服务器端
环境 python3
"""
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
# python3 改动
print("The server is ready to receive")
while 1:
connectSocket , addr = serverSocket.accept()
sentence = connectSocket.recv(1024)
capitalizeSentence =sentence.upper()
connectSocket.send(capitalizeSentence)
connectSocket.close()
实验结果
输入小写字符串,能够返回大写字符串