Python进阶篇:Socket多线程

1. 初识Socket

server和clinet之间的交互方式

 

2. 客户端和服务端的单次交互

 1 ====================================
 2 服务端
 3 
 4 import socket
 5 
 6 
 7 host = '127.0.0.1'
 8 port = 8090
 9 sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
10 sk.bind((host,port))
11 sk.listen(1)
12 
13 conn,addr = sk.accept()
14 accept_data = conn.recv(1024).decode('UTF-8', 'ignore')
15 print(accept_data)
16 feedback_data =("回复\""+accept_data+"\":\n\t你好,我是Server端").encode("utf8")
17 conn.send(feedback_data)
 1 ======================================
 2 客户端
 3 
 4 import socket
 5 
 6 
 7 host = '127.0.0.1'
 8 port = 8090
 9 
10 sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
11 sk.connect((host,port))
12 
13 sk.sendall(("你好,我是Client @Simple").encode("utf8"))
14 data = sk.recv(1024)
15 print(data.decode('UTF-8', 'ignore'))

 

3. 客户端和服务端单线程交互

 1 服务端
 2 
 3 import socket
 4 
 5 
 6 host = '127.0.0.1'
 7 port = 8090
 8 sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 9 sk.bind((host,port))
10 sk.listen(1)
11 
12 while True:
13     conn,addr = sk.accept()
14     while True:
15         accept_data = conn.recv(1024).decode('UTF-8', 'ignore')
16         if not accept_data:
17             break
18         print(accept_data)
19         feedback_data =("回复\""+accept_data+"\":\n\t你好,我是Server端").encode("utf8")
20         conn.sendall(feedback_data)
21 
22     conn.close()
 2 客户端
 3 
 4 import socket,time
 5 
 6 
 7 host = '127.0.0.1'
 8 port = 8090
 9 
10 sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
11 sk.connect((host,port))
12 
13 for i in range(10):
14     sk.sendall(("你好,我是Client No.%d" %i).encode("utf8"))
15     data = sk.recv(1024)
16     print(data.decode('UTF-8', 'ignore'))
17     time.sleep(2)
18     i = i + 1
19 sk.close()

 

4. 多个客户端和服务端的多线程交互

 1 服务端
 2 
 3 import socketserver
 4 
 5 class myTCPhandler(socketserver.BaseRequestHandler):
 6     def handle(self):
 7         while True:
 8             self.data = self.request.recv(1024).decode('UTF-8', 'ignore').strip()
 9             if not self.data : break
10             print(self.data)
11             self.feedback_data =("回复\""+self.data+"\":\n\t你好,我是Server端").encode("utf8")
12             self.request.sendall(self.feedback_data)
13 
14 host = '127.0.0.1'
15 port = 9090
16 server = socketserver.ThreadingTCPServer((host,port),myTCPhandler)
17 server.serve_forever()
 1 客户端1-n
 2 
 3 import socket,time
 4 
 5 
 6 host = '127.0.0.1'
 7 port = 9090
 8 
 9 sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
10 sk.connect((host,port))
11 
12 for i in range(10):
13     sk.sendall(("你好,我是Client No.%d" %i).encode("utf8"))
14     data = sk.recv(1024)
15     print(data.decode('UTF-8', 'ignore'))
16     time.sleep(2)
17     i = i + 1
18 sk.close()

 

posted @ 2016-12-25 15:07  晨柳溪  阅读(8883)  评论(0编辑  收藏  举报