使用多线程实现socket通信
可以通过查看服务端输出的 pid 来比较多进程与多线程。
服务端
from socket import * from threading import Thread import os class Server: code = 'utf-8' family_net = AF_INET type_net = SOCK_STREAM request_queue_size = 5 max_packet_size = 1024 def __init__(self, server_address): self.server_address = server_address self.socket = socket(self.family_net, self.type_net) try: self.server_bind() self.server_listen() except: self.server_close() raise def server_bind(self): self.socket.bind(self.server_address) def server_listen(self): self.socket.listen(self.request_queue_size) def server_close(self): self.socket.close() def run(self): while True: print('waiting...') self.conn, self.addr = self.socket.accept() p = Thread(target=self.sub_p,) p.start() def sub_p(self): while True: print('多线程 pid:%s'% os.getpid()) ret = self.conn.recv(self.max_packet_size).decode(self.code) if not ret: break ret_bytes = ret.upper().encode(self.code) self.conn.send(ret_bytes) if __name__ == '__main__': s = Server(('127.0.0.1', 8099)) s.run()
客户端
from socket import * import os class Client: code = 'utf-8' family_net = AF_INET type_net = SOCK_STREAM max_packet_size = 1024 def __init__(self, server_address): self.server_address = server_address self.socket = socket(self.family_net, self.type_net) try: self.client_connect() except: self.clent_close() raise def client_connect(self): self.socket.connect(self.server_address) def clent_close(self): self.socket.close() def run(self): while 1: ret = input('>>>').strip() if not ret: break self.socket.send(ret.encode(self.code)) data = self.socket.recv(self.max_packet_size) print(data.decode(self.code), os.getpid()) if __name__ == '__main__': c = Client(('127.0.0.1', 8099)) c.run()