threadingSocket 服务器端可以同时接受多个客户端的访问

 server.py文件:

#!/usr/bin/env python
#coding:utf-8
import SocketServer
class  MyServer(SocketServer.BaseRequestHandler):
    def setup(self):
        pass
    def handle(self):
        '''
        print self.request
        print self.client_address
        print self.server
        '''
        conn=self.request
        conn.send('hello!')
        flag=True
        while flag:
            data=conn.recv(1024)
            print data
            if data=='exit':
                flag=False
            conn.send('shaobing')
        conn.close()
    def finish(self):
        pass
 
if __name__ == '__main__':
    server = SocketServer.ThreadingTCPServer(('127.0.0.1',9999),MyServer)
    server.serve_forever()

client.py文件:

#!/usr/bin/env python
#coding:utf-8
import socket,os
ip_port = ('127.0.0.1',9999)
sk = socket.socket()
sk.connect(ip_port)
#container = {'key':'','data':''}
while True:
    input = raw_input('cmd and path:')#cmd和path之间用'/'分割
    cmd,path = input.split('/') 
    file_name = os.path.basename(path)
    file_size=os.stat(path).st_size
    sk.send(cmd+"/"+file_name+'/'+str(file_size))
    send_size = 0
    f= file(path,'rb')
    Flag = True
    while Flag:
        if send_size + 1024 >=file_size:
            data = f.read(file_size-send_size)
            Flag = False
        else:
            data = f.read(1024)
            send_size+=1024
        sk.send(data)
    f.close()
sk.close()

  

 

posted @ 2021-08-13 16:57  noticeable  阅读(115)  评论(0编辑  收藏  举报