python 多线程 并发socket实例
Posted alex_huang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 多线程 并发socket实例相关的知识,希望对你有一定的参考价值。
sever side:
import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): ‘‘‘try内的代码就是要实现的功能,目前是实现小写转大写,可以自定义, try是在客户端结束时不报错 ‘‘‘ try: while True: self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.client_address[0])) print(self.data) self.request.sendall(self.data.upper()) except ConnectionResetError as e: print(e) if __name__ == "__main__": HOST, PORT = "localhost", 6969 server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) server.serve_forever()
client side:
import socket sock = socket.socket() #sock.connect((‘120.78.197.182‘,51102)) sock.connect((‘localhost‘,6969)) flag = False while not flag: data = input(">>:").strip() if data == "b":flag = True if len(data) == 0:continue sock.send(data.encode()) recv_data = sock.recv(8096) print("recv:",recv_data.decode()) # recv_data = b‘‘ # recv_len = 0 # cmd_length = int(sock.recv(8096).decode()) # cli_ack = sock.send(b‘ack‘) # print(‘cmd_len‘,cmd_length) # while recv_len != cmd_length: # data = sock.recv(1024) # recv_data += data # recv_len += len(data) # print(‘recv:‘,recv_data.decode()) sock.close()
以上是关于python 多线程 并发socket实例的主要内容,如果未能解决你的问题,请参考以下文章