标签:
python 多线程
1 #!/usr/bin/env python 2 #coding:UTF8 3 import SocketServer 4 class myserver(SocketServer.BaseRequestHandler): 5 def handle(self): 6 while True: 7 conn = self.request 8 conn.sendall("welcome...") 9 flag = True 10 while flag: 11 data = conn.recv(1024) 12 print data 13 if data == ‘exit‘: 14 conn.sendall(‘finish....‘) 15 flag = False 16 else: 17 conn.sendall("running...") 18 conn.close() 19 20 ipport = (‘127.0.0.1‘,9999) 21 sock = SocketServer.ThreadingTCPServer(ipport,myserver) 22 sock.serve_forever()
发送文件:
1 #!/usr/bin/env python 2 #coding:UTF8 3 import SocketServer 4 class myserver(SocketServer.BaseRequestHandler): 5 def handle(self): 6 while True: 7 conn = self.request ------ client对象 8 conn.sendall("welcome...") ------向client发送数据 9 flag = True 10 f = file(‘d:/22.jpg‘,‘wb‘) 11 while flag: 12 data = conn.recv(1024) 13 f.write() 14 if len(data) <= 1024: 15 print "file recv all" 16 f.close() 17 conn.sendall(‘success‘) 18 conn.close() 19 20 ipport = (‘127.0.0.1‘,9999) 21 sock = SocketServer.ThreadingTCPServer(ipport,myserver) 22 sock.serve_forever()
基础部分
1 Client 2 3 #!/usr/bin/env python 4 #utf8 5 import socket 6 sk = socket.socket() 7 ip_port = (‘127.0.0.1‘,9001) 8 sk.connect(ip_port) 9 10 while True: 11 data = sk.recv(1024) 12 print data 13 if data == ‘close‘: 14 break 15 inp = raw_input("Input:") 16 sk.sendall(inp) 17 sk.close()
1 Server 2 3 #!/usr/bin/env python 4 #coding:uft8 5 import socket 6 sk = socket.socket() 7 8 ip_port = (‘127.0.0.1‘,9001) 9 10 sk.bind(ip_port) 11 sk.listen(4) 12 13 while True: 14 conn,addr = sk.accept() 15 print addr 16 conn.sendall(‘welcome‘) 17 flag = True 18 while flag: 19 data = conn.recv(1024) 20 print data 21 if data == ‘exit‘: 22 conn.sendall(‘finish....‘) 23 flag = False 24 else: 25 conn.sendall("running") 26 conn.colse()
说明一下:多线程处理,当client 访问server,sock,服务器吧请求转交给handle函数,多线程
1 #!/usr/bin/env python 2 #coding:UTF8 3 4 import SocketServer 5 6 class Myserver(SocketServer.BaseRequestHandler): 7 def handle(self): 8 print self.request 9 print self.client_address 10 print self.server 11 12 ‘‘‘ 13 返回的对象 14 <socket._socketobject object at 0x00BC4E68> 15 (‘127.0.0.1‘, 3339) 16 <SocketServer.ThreadingTCPServer instance at 0x00BCC9E0> 17 ‘‘‘ 18 ip_port = (‘127.0.0.1‘,9999) 19 sock = SocketServer.ThreadingTCPServer(ip_port,Myserver) 20 sock.serve_forever()
标签:
原文地址:http://www.cnblogs.com/lnf0701/p/5346449.html