Python TCP socket编程
# TCP通信设计
# 服务器端
# coding=utf-8
from socket import *
# 服务器端
# 创建服务器端套接字对象
serverSocket = socket(AF_INET,SOCK_STREAM)
# 绑定端口
serverSocket.bind(("", 5050))
# 监听
serverSocket.listen()
# 等待客户端的连接
clientSocket, clientInfo = serverSocket.accept()
# 多次通信
while True:
# 接收客户端的消息
receiveData = clientSocket.recv(1024)
print("客户端说:{}".format(receiveData.decode("utf-8")))
# 发送消息
message = input(">>:")
clientSocket.send(message.encode("utf-8"))
# 客户端
# coding=utf-8
from socket import *
# 客户端
# 创建客户端套接字对象
clientSocket = socket(AF_INET, SOCK_STREAM)
# 调用connect方法与服务器建立连接
clientSocket.connect(("127.0.0.1", 5050))
# 通信
while True:
# 客户单发送消息
message = input(">>:")
clientSocket.send(message.encode("utf-8"))
# 客户端接收消息
receiveData = clientSocket.recv(1024)
print("服务器端说:", receiveData.decode("utf-8"))