• python网络编程socket之多进程


    #coding:utf-8
    __author__ = 'similarface'
    
    import os,socket,threading,SocketServer
    SERVER_HOST='localhost'
    SERVER_PORT=0
    BUF_SIZE=1024
    ECHO_MSG='HELLO'
    
    class ForkedClient():
        def __init__(self,ip,port):
            #建立sock
            self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            #连接server
            self.sock.connect((ip,port))
    
        def run(self):
            #获取当前的进程号
            current_process_id=os.getpid()
            print 'PID %s :" "%s"'%(current_process_id,ECHO_MSG)
            sent_data_length = self.sock.send(ECHO_MSG)
            print('发送:%d 长数据' % sent_data_length)
            #sever response
            response=self.sock.recv(BUF_SIZE)
            print "PID %s received: %s" % (current_process_id,response)
    
        def shutdown(self):
            '''
            清理sock的资源
            :return:
            '''
            self.sock.close()
            
    class ForkingServerRequestHandler(SocketServer.BaseRequestHandler):
        def handle(self):
            #接受客户端的数据
            data=self.request.recv(BUF_SIZE)
            #当前的进程号码
            current_process_id=os.getpid()
            #返回的数据包
            response='%s: %s' % (current_process_id, data)
            print "服务器返回 [current_process_id: data] =[%s]" %response
            #发送返回数据
            self.request.send(response)
            return
    
    class ForkingServer(SocketServer.ForkingMixIn,SocketServer.TCPServer):
        pass
    
    def main():
        #建立server
        server=ForkingServer((SERVER_HOST,SERVER_PORT),ForkingServerRequestHandler)
        #获取IP 和 端口
        ip, port = server.server_address # Retrieve the port number
        #服务进程
        server_thread = threading.Thread(target=server.serve_forever)
        #是否放入后台
        server_thread.setDaemon(True) # don't hang on exit
        #启动
        server_thread.start()
        print 'Server loop running PID: %s' %os.getpid()
        # Launch the client(s)
        client1 =  ForkedClient(ip, port)
        client1.run()
        client2 =  ForkedClient(ip, port)
        client2.run()
        # Clean them up
        server.shutdown()
        client1.shutdown()
        client2.shutdown()
        server.socket.close()
    if __name__ == '__main__':
        main()
    

      

  • 相关阅读:
    struts.xml 配置
    result重定向到一个action
    Action类中通过ServlexxxAware接口的方式来获取来获取web资源
    Action类中通过ServletActionContext来获取web资源
    Action类中通过继承xxxAware接口来获取web资源
    Action类中通过ActionContext来获取web资源
    java中日期格式转换
    java类的执行顺序
    批量删除Redis数据库中的Key
    Python等同于PHP的 strip_tags?
  • 原文地址:https://www.cnblogs.com/similarface/p/5526339.html
Copyright © 2020-2023  润新知