Python socket (多线程)

 Server 端 code

import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for socket server.
It is instantiated once per connection be established(request from client) to the socker server.
and must be override the handler() method to implement communication to the client.
"""
connection_account = 0
def handle(self): # redefine method ' handl()' in parent class
MyTCPHandler.connection_account += 1
print ("The %d client connected !" % MyTCPHandler.connection_account ) # How to statistic total No.
# self.request is the TCP socket that connected to the client
while 1:
self.data = self.request.recv(1024).strip()
# if connected client dead, exit loop
if not self.data:
break
print("client: %s \n"
"send: %s") % (self.client_address[0],self.data)
self.request.sendall("GOT IT !") if __name__ == "__main__":
HOST,PORT = "localhost",8888
# creating the socket server and binding to HOST::PORT == "localhost":: 8888
server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
# keeping server running until interrupt (Ctrl + C)
server.serve_forever(poll_interval=0.5)

client 端 code 同单线程

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

上一篇:Java中的锁(转)


下一篇:LeetCode 106 从中序与后序遍历序列构造二叉树