Network programming socket (TCP,IP) socket server runs up, client client client Client service side: Import Socket SK = Socket.socket () #绑定端口号sk. bind (' 127.0.0.1 ', 9999,)) #接收客户请求sk. Listen (5) #链接客户端地址信息while True: # conn,address = sk.accept () conn.sendall (bytes (' Old boy ') , encoding= ' Utf-8 ')) while True: ret_bytes = Conn.recv (1024x768) ret_str = str (ret_bytes,encoding= ' utf-8 ') conn.sendall (bytes (' Your sister ', encoding= ' utf-8 ') print (RET_STR) break print (conn, ' \n\n\n ', address)
File Transfer Server import Socket SK = Socket.socket () #绑定端口号sk. Bind ((' 127.0.0.1 ', 9999,)) #接收客户请求sk. Listen (5) #链接客户端地址信息conn, Address = sk.accept () file_name = Conn.recv (1024x768) str_file_name = str (file_name,encoding = ' Utf-8 ') r = 0f = Open (' D:\E\ semantic\%s '%str_file_name, ' WB ') while True: r + = 1 print (r) ret_bytes = Conn.recv (1024x768) F.write (ret _bytes) F.flush () if ret_bytes: pass else: print (' OK ') break client import time, Ostime.sleep (3) Import socketobj = Socket.socket () obj.connect ((' 127.0.0.1 ', 9999,)) path_name = ' D:\e\ sync file \ desktop Ext/123.xlsx ' file_name = Os.path.basename (path_name) obj.sendall (bytes (file_name,encoding= ' utf-8 ')) Q = 0with Open (Path_name, ' RB ') as F: for I in F: q + = 1 print (q)
Socketserver Multi-Process server: concurrent processing of multiple customer requests using the method: 1, creating the class, must inherit the 2,handle method 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 (1024x768) 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 Server Multi-process File Transfer Server Import Socket,socketserver class myserver (Socketserver. Baserequesthandler): def handle (self): conn = self.request file_name = conn.recv (1024x768) Tr_file_nam E = str (file_name,encoding= ' utf-8 ') f = open (' d:\e\semantic/%s '%tr_file_name, ' WB ') Conn.sendall (bytes (' Greasy 2 ', E ncoding= ' Utf-8 ')) R = False ww = 0 While not r:data = Conn.recv (1024x768) F.write ( Data) if DATA:WW + = 1 print (ww) else:r = True if __n ame__ = = ' __main__ ': Server = Socketserver. Threadingtcpserver ((' 127.0.0.1 ', 9999), MyServer) Server.serve_forever () client import time,ostime.sleep (2) Import Socketobj = Socket.socket () obj.connect ((' 127.0.0.1 ', 9999,)) Path_name = ' D:\E\ sync file \ Fitting Banner\ product Cutout/Supplies 2.psd ' file_name = Os.path.basename (path_name) obj.sendall (bytes (file_name,encoding= ' utf-8 ')) print (str (OBJ.RECV (1024x768), encoding= ' Utf-8 ')) Q = 0with open (path_name, ' RB ') as F: For i in F:q + = 1 print (q) obj.sendall (i) obj.close ()
Socketserver Sub-block recording