• python单线程下实现多个socket并发


    先看服务端的代码

    import sys
    # import socket
    import time
    import gevent
    from gevent import socket
    from gevent import monkey
    monkey.patch_all()
    #类似于python中的黑魔法,把很多模块的阻塞的变成非阻塞的,比如socket中的rece和send都变
    # 为不阻塞了
    
    
    def server(port):
        s = socket.socket()
        s.bind(("127.0.0.1",port))
        s.listen(2000)
        while True:
            cli,add = s.accept()
            gevent.spawn(handle_request,cli)
            #通过gevent的启动一个协程,把客户端的socket对象传进去
    def handle_request(s):
        try:
            while True:
                data = s.recv(1024)
                print("收到的信息:",str(data,encoding="utf-8"))
                s.send(data)
                if not data:
                    s.shutdown(socket.SHUT_WR)
                    #把和客户端这个链接销毁
        except Exception as ex:
            print(ex)
        finally:
            s.close()
    
    if __name__ == '__main__':
        server(8000)
    

     

    在看客户端的代码,分别使用多线程和多进程实现

    import socket
    import gevent
    import threading
    import multiprocessing
    '''
    ip_bind = ("127.0.0.1",8000)
    c = socket.socket()
    c.connect(ip_bind)
    while True:
        data = input("客户端:")
        c.send(bytes(data,encoding="utf-8"))
        data = c.recv(1024)
        print("服务端:",str(data,encoding="utf-8"))
    
    c.close()
    '''
    import socket
    import gevent
    ip_bind = ("127.0.0.1",8000)
    c = socket.socket()
    c.connect(ip_bind)
    def f(n):
        while True:
            # c.send(bytes(n,encoding="utf-8"))
            data = str(n)
            c.send(bytes(data,encoding="utf-8"))
            data = c.recv(1024)
            print("server:",str(data,encoding="utf-8"))
        c.close()
    x = []
    if __name__ == '__main__':
        l = []
        """
        多线程实现并发客户端
            for i in range(500):
             t = threading.Thread(target=f,args=[str(i),])
             t.start()
             l.append(t)
        for t in l:
             t.join()
    
        """
        # 多进程实现并发客户端
        for i in range(100):
            p = multiprocessing.Process(target=f,args=[i,])
            p.start()
            l.append(p)
        for p in l:
            p.join()
    

      

  • 相关阅读:
    java后台对上传的图片进行压缩
    Reflections框架,类扫描工具
    commons-httpclient和org.apache.httpcomponents的区别
    sql里面插入语句insert后面的values关键字可省略
    Callable接口、Runable接口、Future接口
    Java多线程之Callable接口的实现
    说说Runnable与Callable
    论坛贴吧问题:如何终止运行时间超时的线程
    使用Future停止超时任务
    spring的@Transactional注解详细用法
  • 原文地址:https://www.cnblogs.com/bainianminguo/p/7441907.html
Copyright © 2020-2023  润新知