DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Multi-thread Echo Server: Python Version


源代码(mulThrServ.py):

import socket import threading import SocketServer class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(1024) cur_thread = threading.current_thread() print "cur_thread: " + cur_thread.name print "data: " + data response = "{}: {}".format(cur_thread.name, data) self.request.sendall(response) class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass def client(ip, port, message): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) try: sock.sendall(message) response = sock.recv(1024) print "Received: {}".format(response) finally: sock.close() if name == "main": # Port 0 means to select an arbitrary unused port HOST, PORT = "localhost", 0 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) ip, port = server.server_address # Start a thread with the server -- that thread will then start one # more thread for each request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread terminates server_thread.daemon = True server_thread.start() print "Server loop running in thread:", server_thread.name client(ip, port, "Hello World 1") client(ip, port, "Hello World 2") client(ip, port, "Hello World 3") server.shutdown()

运行(Ubuntu Server 12.04):

$ python mulThrServ.py

Server loop running in thread: Thread-1

Received: Thread-2: Hello World 1

Received: Thread-3: Hello World 2

Received: Thread-4: Hello World 3

可以看到对客户端的每次连接,服务端都启动了新的线程进行处理。此程序在python 2.7上运行完成,在python 2.6上运行时字符串的format函数写法与2.7不同,需要修改。



Published

Feb 10, 2013

Last Updated

Feb 10, 2013

Category

Tech

Tags

  • echo server 2
  • multi-thread 1
  • Python 136

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor