python实现多个客户端与服务器端持续交互程序
转载
1. 客户端
tcp_client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_client_socket.connect(('192.168.1.10',8080))
# encode(把字符串转为bytes) decode(把bytes转为字符串)
data = data.encode('gbk')
tcp_client_socket.send(data)
# 4 接收服务器返回的数据 recv(字节大小)
recv_data = tcp_client_socket.recv(1024).decode('gbk')
tcp_client_socket.close()
2. 服务器端
# 定义handle_client_request 循环以保持与客户端的连接,并能持续互相传递消息
def handle_client_request(service_client_socket,ip_port):
recv_data = service_client_socket.recv(1024)
print(recv_data.decode('gbk'),ip_port) # 将二进制格式转换为'gbk'
back = f'自动回复:欢迎,您发送的数据为{recv_data.decode("gbk")}'
service_client_socket.send(back.encode('gbk')) # 将'gbk'格式转换为二进制
service_client_socket.close()
if __name__ == '__main__':
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
# 2 绑定IP和端口,ip不写或写'127.0.0.1'都是主机本身
tcp_server_socket.bind(('',8080))
tcp_server_socket.listen(5)
service_client_socket, ip_port = tcp_server_socket.accept()
sub_thread = threading.Thread(target=handle_client_request,args=(service_client_socket,ip_port))
sub_thread.setDaemon(True)
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。