# 服务器端 import socket # 实例化一个socket对象,并指定网络层协议、传输层协议 socket_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 绑定IP、端口号 socket_server.bind((‘127.0.0.1‘,8080),) # 同一时间内能够接收的请求 socket_server.listen(5) # 等待连接 connect,client_address = socket_server.accept() # 设置接收消息,最大限制为1024 receive_mag = connect.recv(1024) print(‘收到客户端的消息:%s‘ % receive_mag.decode(‘UTF-8‘)) # 发送数据 connect.send(receive_mag.upper()) # 关闭连接 connect.close() # 客户端 import socket socket_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 连接服务端,指定IP、端口号 socket_client.connect((‘127.0.0.1‘,8080)) # 向服务端发消息 socket_client.send(‘Hello,I am client!‘.encode(‘utf-8‘)) data = socket_client.recv(1024) print(‘接收到服务器的消息:%s‘ % data.decode(‘utf-8‘)) socket_client.close()
3.基于TCP的套接字连接循环和通信循环
# 服务器端 import socket phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) phone.bind((‘127.0.0.1‘,8080)) phone.listen(5) while True: # 连接循环 connect,client_address = phone.accept() print(‘客户端:‘,client_address) while True: # 通信循环 try: msg = connect.recv(1024) print(‘客户端消息:‘,msg) connect.send(msg+b‘from server‘) except ConnectionResetError: break connect.close() phone.close() # 客户端 import socket phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM) phone.connect((‘127.0.0.1‘,8080)) # 拨电话,地址为服务端的ip和端口 while True: msg = input(‘>>>).strip() phone.send(msg.encode(‘utf-8‘)) # 发消息 data = phone.recv(1024) #收消息 print(data.decode(‘utf-8‘)) phone.close()
原文:https://www.cnblogs.com/mdzzbojo/p/8981571.html