Python Socket多线程并发原理及实现
程序员文章站
2022-03-02 12:23:45
1.socketserver模块编写的tcp服务器端代码 socketserver原理图服务端:import socketserver #导入socketserver,多线程并发由此类实现...
1.socketserver模块编写的tcp服务器端代码
socketserver原理图
服务端:
import socketserver #导入socketserver,多线程并发由此类实现 class mysockserver(socketserver.baserequesthandler): #定义一个类 def handle(self): #handle(self)方法是必须要定义的,可以看上面的说明 print 'got a new connection from', self.client_address while true: data = self.request.recv(1024) #需要通过self的方法调用数据接收函数 if not data:break print 'recv:', data self.request.send(data.upper()) #需要通过self的方法调用数据接收函数 if __name__ == '__main__': #并非一定要用这样的方式,只是建议这样使用 host = '' #定义侦听本地地址口(多个ip地址情况下),这里表示侦听所有 port = 50007 #server端开放的服务端口 s = socketserver.threadingtcpserver((host, port), mysockserver) #调用socketserver模块的多线程并发函数 s.serve_forever() #持续接受客户端的连接
客户端:
import socket host = '192.168.1.13' port = 50007 s = socket.socket(socket.af_inet, socket.sock_stream) s.connect((host, port)) while true: user_input = raw_input('msg to send:').strip() s.sendall(user_input) data = s.recv(1024) print 'received', repr(data) s.close()
2.基于python socketserver的实现的ftp程序
服务端:
import socketserver import struct import json import os class ftpserver(socketserver.baserequesthandler): coding='utf-8' server_dir='file_upload' max_packet_size=1024 base_dir=os.path.dirname(os.path.abspath(__file__)) def handle(self): print(self.request) while true: data=self.request.recv(4) data_len=struct.unpack('i',data)[0] head_json=self.request.recv(data_len).decode(self.coding) head_dic=json.loads(head_json) # print(head_dic) cmd=head_dic['cmd'] if hasattr(self,cmd): func=getattr(self,cmd) func(head_dic) def put(self,args): file_path = os.path.normpath(os.path.join( self.base_dir, self.server_dir, args['filename'] )) filesize = args['filesize'] recv_size = 0 print('----->', file_path) with open(file_path, 'wb') as f: while recv_size < filesize: recv_data = self.request.recv(self.max_packet_size) f.write(recv_data) recv_size += len(recv_data) print('recvsize:%s filesize:%s' % (recv_size, filesize)) ftpserver=socketserver.threadingtcpserver(('127.0.0.1',8080),ftpserver) ftpserver.serve_forever()
客户端:
import socket import struct import json import os class mytcpclient: address_family = socket.af_inet socket_type = socket.sock_stream allow_reuse_address = false max_packet_size = 8192 coding='utf-8' request_queue_size = 5 def __init__(self, server_address, connect=true): self.server_address=server_address self.socket = socket.socket(self.address_family, self.socket_type) if connect: try: self.client_connect() except: self.client_close() raise def client_connect(self): self.socket.connect(self.server_address) def client_close(self): self.socket.close() def run(self): while true: inp=input(">>: ").strip() if not inp:continue l=inp.split() cmd=l[0] if hasattr(self,cmd): func=getattr(self,cmd) func(l) def put(self,args): cmd=args[0] filename=args[1] if not os.path.isfile(filename): print('file:%s is not exists' %filename) return else: filesize=os.path.getsize(filename) head_dic={'cmd':cmd,'filename':os.path.basename(filename),'filesize':filesize} print(head_dic) head_json=json.dumps(head_dic) head_json_bytes=bytes(head_json,encoding=self.coding) head_struct=struct.pack('i',len(head_json_bytes)) self.socket.send(head_struct) self.socket.send(head_json_bytes) send_size=0 with open(filename,'rb') as f: for line in f: self.socket.send(line) send_size+=len(line) print(send_size) else: print('upload successful') client=mytcpclient(('127.0.0.1',8080)) client.run()
以上就是python socket多线程并发原理及实现的详细内容,更多关于python socket多线程并发的资料请关注其它相关文章!
下一篇: Python文件名匹配与文件复制的实现