zoukankan      html  css  js  c++  java
  • 实现socket并发的几种方法

    # 使用多进程实现socket聊天并发-server
    #服务端
    import socket
    from multiprocessing import Process
    
    def server(conn,addr):
        while True:
            try:
                msg=conn.recv(1024)
                conn.send(msg.upper())
            except Exception as f:
                print(f)
                conn.close()
                break
    if __name__ == '__main__':
        sk=socket.socket()
        sk.bind(("127.0.0.1",8000))
        sk.listen(5)
        while True:
            conn,addr=sk.accept()
            p=Process(target=server,args=(conn,addr))
            p.start()
    # 使用多进程实现socket聊天并发-server
    import socket
    from threading import Thread
    
    def server(conn,addr):
        while True:
            try:
                msg=conn.recv(1024)
                conn.send(msg.upper())
            except Exception as f:
                print(f)
                conn.close()
                break
    if __name__ == '__main__':
        sk=socket.socket()
        sk.bind(("127.0.0.1",8000))
        sk.listen(5)
        while True:
            conn,addr=sk.accept()
            t=Thread(target=server,args=(conn,addr))
            t.start()
    # 使用协程实现socket聊天并发 - server
    from gevent import monkey
    monkey.patch_all()
    import socket
    import gevent
    def talk(conn):
    	while True:
    		msg = conn.recv(1024).decode()
    		ret_msg = msg.upper().encode()
    		conn.send(ret_msg)
    
    sk = socket.socket()
    sk.bind(('127.0.0.1',8000))
    sk.listen()
    
    while True:
    	conn,_ = sk.accept()
    	g = gevent.spawn(talk,conn)
    # 使用非阻塞IO实现socket聊天并发 - server
    #服务端
    from socket import *
    import time
    s=socket(AF_INET,SOCK_STREAM)
    s.bind(('127.0.0.1',8080))
    s.listen(5)
    s.setblocking(False) #设置socket的接口为非阻塞
    conn_l=[]
    del_l=[]
    while True:
        try:
            conn,addr=s.accept()
            conn_l.append(conn)
        except BlockingIOError:
            print(conn_l)
            for conn in conn_l:
                try:
                    data=conn.recv(1024)
                    if not data:
                        del_l.append(conn)
                        continue
                    conn.send(data.upper())
                except BlockingIOError:
                    pass
                except ConnectionResetError:
                    del_l.append(conn)
    
            for conn in del_l:
                conn_l.remove(conn)
                conn.close()
            del_l=[]
    # 使用IO多路复用实现socket聊天并发 - server
    #服务端
    from socket import *
    import select
    
    s=socket(AF_INET,SOCK_STREAM)
    s.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
    s.bind(('127.0.0.1',8081))
    s.listen(5)
    s.setblocking(False) #设置socket的接口为非阻塞
    read_l=[s,]
    while True:
        r_l,w_l,x_l=select.select(read_l,[],[])
        print(r_l)
        for ready_obj in r_l:
            if ready_obj == s:
                conn,addr=ready_obj.accept() #此时的ready_obj等于s
                read_l.append(conn)
            else:
                try:
                    data=ready_obj.recv(1024) #此时的ready_obj等于conn
                    if not data:
                        ready_obj.close()
                        read_l.remove(ready_obj)
                        continue
                    ready_obj.send(data.upper())
                except ConnectionResetError:
                    ready_obj.close()
                    read_l.remove(ready_obj)
    # 使用socketserver实现socket聊天并发 - server
    import socketserver
    class Myserver(socketserver.BaseRequestHandler):
        def handle(self):
            self.data = self.request.recv(1024).strip()
            print("{} wrote:".format(self.client_address[0]))
            print(self.data)
            self.request.sendall(self.data.upper())
    
    if __name__ == "__main__":
        HOST, PORT = "127.0.0.1", 9999
    
        # 设置allow_reuse_address允许服务器重用地址
        socketserver.TCPServer.allow_reuse_address = True
        # 创建一个server, 将服务地址绑定到127.0.0.1:9999
        server = socketserver.TCPServer((HOST, PORT),Myserver)
        # 让server永远运行下去,除非强制停止程序
        server.serve_forever()
    

      

  • 相关阅读:
    字符串转数字的hash函数-布隆过滤器
    javascript实现字符查询之kmp算法
    毫秒查询9位数qq号码是否存在-BitMap算法应用
    bitMap算法将字符串映射成数字,同时可以将数字映射成字符串-javascript
    js数字格式化为千分位
    浅谈BST(二叉查找树)
    CSP2019 游记
    2019.10.20模拟赛总结
    P2827 蚯蚓
    原生js解决简单轮播图的切换
  • 原文地址:https://www.cnblogs.com/ellisonzhang/p/10473172.html
Copyright © 2011-2022 走看看