這篇文章給大家介紹利用 Socket怎么在Python項(xiàng)目中實(shí)現(xiàn)一個多線程并發(fā)功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
成都創(chuàng)新互聯(lián)公司作為成都網(wǎng)站建設(shè)公司,專注重慶網(wǎng)站建設(shè)公司、網(wǎng)站設(shè)計(jì),有關(guān)企業(yè)網(wǎng)站制作方案、改版、費(fèi)用等問題,行業(yè)涉及成都墻體彩繪等多個領(lǐng)域,已為上千家企業(yè)服務(wù),得到了客戶的尊重與認(rèn)可。Socketserver原理圖
服務(wù)端:
import SocketServer #導(dǎo)入SocketServer,多線程并發(fā)由此類實(shí)現(xiàn) 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的方法調(diào)用數(shù)據(jù)接收函數(shù) if not data:break print 'recv:', data self.request.send(data.upper()) #需要通過self的方法調(diào)用數(shù)據(jù)接收函數(shù) if __name__ == '__main__': #并非一定要用這樣的方式,只是建議這樣使用 HOST = '' #定義偵聽本地地址口(多個IP地址情況下),這里表示偵聽所有 PORT = 50007 #Server端開放的服務(wù)端口 s = SocketServer.ThreadingTCPServer((HOST, PORT), MySockServer) #調(diào)用SocketServer模塊的多線程并發(fā)函數(shù) s.serve_forever() #持續(xù)接受客戶端的連接
客戶端:
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()
服務(wù)端:
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()
關(guān)于利用 Socket怎么在Python項(xiàng)目中實(shí)現(xiàn)一個多線程并發(fā)功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。