zoukankan      html  css  js  c++  java
  • python 网络编程第二版

    为服务端增加多进程解决方案

    1、server端代码如下:

    #!/usr/bin/python
    #!coding:utf-8
    
    import os,sys,time
    from socket import *
    
    def handleClient(conn):
        print '[info]    handleClient is :{0}'.format(os.getpid())
        while True:
            data = conn.recv(1024)
            if not data : print '[info]    handleClient client is stoped ..';break
            print '[info]    handleClient recive this --> {0}'.format(data.encode())
            reply='[info]    handleClient this is the information from server --> {0}'.format(data.decode())
            conn.send(reply.encode())
        conn.close()
        os._exit(0)
    
    if __name__ == "__main__":
        hostIp='127.0.0.1'
        port=2048
        sock=socket(AF_INET,SOCK_STREAM)
        sock.bind((hostIp,port))
        sock.listen(5)
        print '[info]    parent pid is :{0} start listen {1}'.format(os.getpid(),(hostIp,port))
        while True:
            conn,addr=sock.accept()
            print '[info]    parent get a client {0}'.format(addr)
            cpid = os.fork()
            if cpid == 0: handleClient(conn)

    2、client端代码如下:

    #!/usr/bin/python
    #!coding:utf-8
    
    from socket import *
    import os,sys
    
    if __name__ == "__main__":
        #定义套接字
        hostIp='127.0.0.1'
        port=2048
        sock=socket(AF_INET,SOCK_STREAM)
        messages=['hello I am a client']
        messages=messages+sys.argv[1:]
        sock.connect((hostIp,port))
        print '[info]    已经连接到server '
        
        for message in messages:
            sock.send(message.encode())
            print sock.recv(1024).decode()
        sock.close()
        
  • 相关阅读:
    list 、set 、map 粗浅性能对比分析
    利用 Windows Azure 实现“云优先”
    利用代码改变世界 #AzureDev
    openssl 加密
    openssl 加密
    tls和ssl
    tls和ssl
    从输入框获取输入,插入到文本框
    从输入框获取输入,插入到文本框
    windows expect-5.21r1b1-setup.exe 下载链接
  • 原文地址:https://www.cnblogs.com/JiangLe/p/5094844.html
Copyright © 2011-2022 走看看