Soket编程:客户端-服务端单线程通信
客户端:
# 导入socket模块 import socket # 创建socket对象 ClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 获取本机IP地址 host = socket.gethostbyname(socket.gethostname()) # 设置连接IP的端口 port = 12580 # 将IP地址和端口设置为元组,方便使用 my_data = (host, port) # 链接服务器 ClientSocket.connect(my_data) while True: User_Message = input("向服务端说:") ClientSocket.send(User_Message.encode("utf-8")) Message = ClientSocket.recv(2048) print("服务端说:" + str(Message.decode("utf-8"))) ClientSocket.close(
服务端:
# 导入socket模块 import socket # 创建服务器socket对象 ServicesSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置服务端的IP地址 host = socket.gethostbyname(socket.gethostname()) # 设置服务端的端口 port = 12580 # 将IP地址和端口设置为元组,方便使用 my_data = (host, port) # 绑定IP和端口 ServicesSocket.bind(my_data) # 设置最大连接数 ServicesSocket.listen(5) while True: # 等待客户 ClientSocket, addr = ServicesSocket.accept() while True: # 接收客户端传输过来消息,最大为2048字节 Message = ClientSocket.recv(2048) print("客户端说:" + str(Message.decode("utf-8"))) Services_Message = input("向客户端说:") # 向客户端发送数据 ClientSocket.send(Services_Message.encode("utf-8")) ServicesSocket.close()
运行结果:首先启动服务端,在启动客户端发送信息