• python2.7_2.2_在套接字服务器上使用ForkingMixIn


    Linux系统下才能用本程序。因为有Frok新的进程。。。。

    代码如下:

    # -*- coding: utf-8 -*-
    
    import os
    import socket
    import threading
    import SocketServer
    
    SERVER_HOST = 'localhost'
    SERVER_PORT = 0
    BUF_SIZE = 1024
    ECHO_MSG = 'Hello echo server!'
    
    
    class ForkingClient():
        """一个客户端用来测试forking server"""
    
        def __init__(self, ip, port):
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((ip, port))
    
        def run(self):
            """客户端playing with服务器"""
            # 发送数据到服务端
            current_process_id = os.getpid()
            print 'PID %s Sending echo message to the server:"%s"' % (current_process_id, ECHO_MSG)
            sent_data_length = self.sock.send(ECHO_MSG)
            print 'Sent:%d characters, so far ...' % sent_data_length
    
            # 显示服务端回应
            response = self.sock.recv(BUF_SIZE)
            print 'PID %s received:%s' % (current_process_id, response[5:])
    
        def shutdown(self):
            """清空客户端套接字"""
            self.sock.close()
    
    
    class ForkingServerRequestHandler(SocketServer.BaseRequestHandler):
        def handle(self):
            # 发送回显回客户端
            data = self.request.recv(BUF_SIZE)
            current_process_id = os.getegid()
            response = '%s:%s' % (current_process_id, data)
            print 'Server sending response [current_process_id:data] = [%s]' %response
            self.request.send(response)
            return
    
    
    class ForkingServer(SocketServer.ForkingMixIn,
                        SocketServer.TCPServer,
                        ):
        pass
    
    
    def main():
        server = ForkingServer((SERVER_HOST, SERVER_PORT), ForkingServerRequestHandler)
        ip, port = server.server_address
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.setDaemon(True)
        server_thread.start()
        print 'Server loop running PID:%s' % os.getpid()
    
        client1 = ForkingClient(ip, port)
        client1.run()
    
        client2 = ForkingClient(ip, port)
        client2.run()
    
        server.shutdown()
    
        client1.shutdown()
        client2.shutdown()
        server.socket.close()
    
    if __name__ == '__main__':
        main()
  • 相关阅读:
    .NET Framework 1.13.5 版本安装包下载链接
    可遇不可求的Question之MYSQL获取自增ID的四种方法篇
    20110917 晴
    北海道 7天6夜 自助游
    想你了
    猫忘带电话了
    [转载经验] 探亲签证申请
    帮忙打印
    打印机
    20110910 晴
  • 原文地址:https://www.cnblogs.com/jsben/p/5167759.html
Copyright © 2020-2023  润新知