Python socket (多线程)

SocketServer多线程服务端与客户端实现
本文介绍了一个使用Python SocketServer模块创建多线程TCP服务器的具体实现过程,并展示了如何统计连接到服务器的客户端数量及服务器与客户端之间的基本交互。
 1 Server 端 code
 2 
 3 import SocketServer
 4 class MyTCPHandler(SocketServer.BaseRequestHandler):
 5     """
 6     The RequestHandler class for socket server.
 7     It is instantiated once per connection be established(request from client) to the socker server.
 8     and must be override the handler() method to implement communication to the client.
 9     """
10     connection_account = 0
11     def handle(self):    # redefine method ' handl()' in parent class
12         MyTCPHandler.connection_account += 1
13         print ("The %d client connected !" % MyTCPHandler.connection_account )  # How to statistic total No.
14         # self.request is the TCP socket that connected to the client
15         while 1:
16             self.data = self.request.recv(1024).strip()
17             # if connected client dead, exit loop
18             if not self.data:
19                 break
20             print("client: %s \n"
21                    "send: %s") % (self.client_address[0],self.data)
22             self.request.sendall("GOT IT !")
23 
24 if __name__ == "__main__":
25     HOST,PORT = "localhost",8888
26     # creating the socket server and  binding to HOST::PORT == "localhost":: 8888
27     server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
28     # keeping server running until interrupt (Ctrl + C)
29     server.serve_forever(poll_interval=0.5)

 

    client 端 code 同单线程

            参考博文,  http://www.cnblogs.com/zzyzz/p/5581503.html

 

转载于:https://www.cnblogs.com/zzyzz/p/5728551.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值