#!/usr/bin/env python
#--coding:utf8--
'''
首先创建一个服务器线程,并在后台启动。然后启动三个测试客户端,向服务器发
送消息。作为响应,服务器把消息回显给客户端。在服务器请求处理类的handle()方法中,我
们取回了当前线程的信息并将其打印出来,这些信息在每次客户端连接中都不同。
'''

import os,socket,threading,SocketServer

SERVER_HOST = 'localhost'
SERVER_PORT = 0 # tells the kernel to pickup a port dynamically
BUF_SIZE = 1024

def client(ip, port, message):
    """ A client to test threading mixin server"""
    # Connect to the server
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    try:
        sock.sendall(message)
        response = sock.recv(BUF_SIZE)
        print("Client received : %s" %response)
    finally:
        sock.close()

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    """ An example of threaded TCP request handler """
    def handle(self):
        data = self.request.recv(1024)
        current_thread = threading.current_thread()
        response = "%s: %s" %(current_thread.name, data)
        self.request.sendall(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    """
    Nothing to add here, inherited everything necessary from parents
    ThreadedTCPServer继承自TCPServer和TheadingMixIn。客户端连接这个多线程版服务器时,会创建一个新线程。
    """
    pass

if __name__ == '__main__':
    # Run server
    server = ThreadedTCPServer((SERVER_HOST, SERVER_PORT),ThreadedTCPRequestHandler)
    ip, port = server.server_address # retrieve ip address
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.daemon = True
    server_thread.start()
    print "Server loop running on thread: %s" %server_thread.name
    # Run clients
    client(ip, port, "Hello from client 1")
    client(ip, port, "Hello from client 2")
    client(ip, port, "Hello from client 3")
    # Server cleanup
    server.shutdown()



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐