python 并发socket

Posted arrowxiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 并发socket相关的知识,希望对你有一定的参考价值。

import socket
import selectors
import threading
import time
selector = selectors.DefaultSelector()

socket_server = socket.socket()
address_server = (0.0.0.0,8080)
socket_server.bind(address_server)
socket_server.listen(1000)


def wokter(socket_ser):  #多线程套接字
    while True:
        massage = socket_ser.recv(1024)
        if massage:
            socket_ser.send(massage)
        else:
            socket_ser.close()

while True:
    socket_ser, address = socket_server.accept()
    socket_thre =threading.Thread(target=wokter, args=(socket_ser,))
    socket_thre.start()


def server_read(connect): #epoll的socket
    massage = connect.recv(1024)
    if massage:
        connect.send(massage)
    else:
        selector.unregister(connect)#清除注册
        connect.close()

def accept(socket_server):
    socket_ser, address = socket_server.accept()
    socket_ser.setblocking(False)
    selector.register(socket_ser, selectors.EVENT_READ, server_read)#注册事件回调socket连接
selector.register(socket_server, selectors.EVENT_READ, accept)#注册事件回调socket对象

while True:
    events = selector.select()#查询所有准备好的事件,一个二元组列表
    for key,massk in events:
        callback = key.data  #拿到回调函数
        sock = key.fileobj   #拿到注册的那个socket
        callback(sock)       #回调执行

 

以上是关于python 并发socket的主要内容,如果未能解决你的问题,请参考以下文章

python 并发socket

python之多并发socket

python-gevent模块实现socket大并发

python-gevent模块实现socket大并发

python基础之socket编程part2---粘包和并发

10.python网络编程(socket server 实现并发 part 2)