• Python并发编程-多进程socketserver简易版


    普通版的socketserver

    #server.py
    
    import socket
    
    sk = socket.socket()
    sk.bind(('127.0.0.1',8080))#建立连接
    sk.listen() #打开监听
    while True:
        conn,addr = sk.accept() #接收到一个连接和一个地址
        ret = 'hi'.encode('utf-8')
        conn.send(ret)
        msg = conn.recv(1024).decode('utf-8')
        print(msg)
        conn.close()
    sk.close()
    
    #Client.py
    import socket
    
    sk = socket.socket()
    sk.connect(('127.0.0.1',8080))
    
    msg = sk.recv(1024).decode('utf-8')
    print(msg)
    msg2 = input('>>>').encode('utf-8')
    sk.send(msg2)
    
    sk.close()
    

    简易多进程socketserver

    ###server.py
    import socket
    from multiprocessing import Process
    #主要的不同是利用了函数和子进程,这里建立了函数
    def serve(conn):
        ret = 'hi'.encode('utf-8')
        conn.send(ret)
        msg = conn.recv(1024).decode('utf-8')
        print(msg)
        conn.close()
    
    if __name__ == '__main__':
        sk = socket.socket()
        sk.bind(('127.0.0.1',8080))#建立连接
        sk.listen() #打开监听
        while True:
            conn,addr = sk.accept() #接收到一个连接和一个地址
    #开启子进程
            p = Process(target=serve,args =(conn,))
            p.start()
        sk.close()
    
    ###client.py
    import socket
    
    sk = socket.socket()
    sk.connect(('127.0.0.1',8080))
    
    msg = sk.recv(1024).decode('utf-8')
    print(msg)
    msg2 = input('>>>').encode('utf-8')
    sk.send(msg2)
    
    sk.close()
  • 相关阅读:
    中断解析
    中断分类
    中断分类
    在iOS开发中使用FMDB
    大数据权限授权管理框架:Apache Sentry和Ranger
    Flink FileSystem的connector分析
    Flink FileSystem的connector分析
    Flink JobManager的HA原理分析
    Flink JobManager的HA原理分析
    Flink的State概述
  • 原文地址:https://www.cnblogs.com/konglinqingfeng/p/9686159.html
Copyright © 2020-2023  润新知