socketserver服务器
''' 网络编程 Socket(TCP,IP)套接字 服务端 运行起来, 客户端 客户端 客户端 客户端 服务端: import socket sk = socket.socket() #绑定端口号 sk.bind(('127.0.0.1',9999,)) #接收客户请求 sk.listen(5) #链接客户端地址信息 while True: # conn,address = sk.accept() conn.sendall(bytes('老男孩',encoding='utf-8')) while True: ret_bytes = conn.recv(1024) ret_str = str(ret_bytes,encoding='utf-8') conn.sendall(bytes('你妹',encoding='utf-8')) print(ret_str) break print(conn,'\n\n\n',address) 客户端 import socket obj = socket.socket() obj.connect(('127.0.0.1',9999,)) #等待接受服务器消息 r = obj.recv(1024) print(str(r,encoding='utf-8')) obj.sendall(bytes('呵呵',encoding='utf-8')) r1 = obj.recv(1024) print(str(r1,encoding='utf-8')) obj.close() 文件传输 服务端 import socket sk = socket.socket() #绑定端口号 sk.bind(('127.0.0.1',9999,)) #接收客户请求 sk.listen(5) #链接客户端地址信息 conn,address = sk.accept() file_name = conn.recv(1024) str_file_name = str(file_name,encoding = 'utf-8') r = 0 f = open('D:\E\semantic\%s'%str_file_name,'wb') while True: r += 1 print(r) ret_bytes = conn.recv(1024) f.write(ret_bytes) f.flush() if ret_bytes: pass else: print('ok') break 客户端 import time,os time.sleep(3) import socket obj = socket.socket() obj.connect(('127.0.0.1',9999,)) path_name = 'D:\e\同步文件\桌面 EXT/楚楚街 主推款.xlsx' file_name = os.path.basename(path_name) obj.sendall(bytes(file_name,encoding='utf-8')) q = 0 with open(path_name,'rb') as f: for i in f: q += 1 print(q) obj.sendall(i) obj.close() socketserver多进程服务器: 并发处理多个客户请求 使用方法: 1,创建类,必须继承 2,handle方法 3,server.serve_forever import socket,socketserver class myserver(socketserver.BaseRequestHandler): def handle(self): conn = self.request conn.sendall(bytes('hello',encoding='utf-8')) ret = conn.recv(1024) ret_str = str(ret,encoding='utf-8') print(ret_str) if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',9999),myserver) server.serve_forever() socketserver 服务器多进程 文件传输 服务器 import socket,socketserver class myserver(socketserver.BaseRequestHandler): def handle(self): conn = self.request file_name = conn.recv(1024) tr_file_name = str(file_name,encoding='utf-8') f = open('D:\E\semantic/%s'%tr_file_name,'wb') conn.sendall(bytes('腻2',encoding='utf-8')) r = False ww = 0 while not r: data = conn.recv(1024) f.write(data) if data: ww += 1 print(ww) else: r = True if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1',9999),myserver) server.serve_forever() 客户端 import time,os time.sleep(2) import socket obj = socket.socket() obj.connect(('127.0.0.1',9999,)) path_name = 'D:\E\同步文件\装修Banner\产品抠图/用品2.psd' file_name = os.path.basename(path_name) obj.sendall(bytes(file_name,encoding='utf-8')) print(str(obj.recv(1024),encoding='utf-8')) q = 0 with open(path_name,'rb') as f: for i in f: q += 1 print(q) obj.sendall(i) obj.close() '''