python2.7_2.2_在套接字服务器上使用ForkingMixIn
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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()
以上是关于python2.7_2.2_在套接字服务器上使用ForkingMixIn的主要内容,如果未能解决你的问题,请参考以下文章
使用__future__实现从python2.7到python3.x的过渡
AttributeError: (Class) object has no attribute '__name__' 创建 ModelForms [Django & Python2.7]