码迷,mamicode.com
首页 > 编程语言 > 详细

python 并发socket

时间:2018-05-04 14:13:06      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:span   read   close   连接   target   python   sele   selector   soc   

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

标签:span   read   close   连接   target   python   sele   selector   soc   

原文地址:https://www.cnblogs.com/arrow-kejin/p/8989930.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!