码迷,mamicode.com
首页 > 其他好文 > 详细

selectors模块

时间:2018-11-19 21:34:47      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:连接   sele   ack   range   received   connect   活动   res   net   

import selectors
import socket

sel = selectors.DefaultSelector()


def accept(sock, mask):
conn, addr = sock.accept() # Should be ready
print(‘accepted‘, conn, ‘from‘, addr,mask)
conn.setblocking(False)
sel.register(conn, selectors.EVENT_READ, read) #新连接注册read回调函数


def read(conn, mask):
data = conn.recv(1024) # Should be ready
if data:
print(‘echoing‘, repr(data), ‘to‘, conn)
conn.send(data) # Hope it won‘t block
else:
print(‘closing‘, conn)
sel.unregister(conn)
conn.close()


sock = socket.socket()
sock.bind((‘localhost‘, 9999))
sock.listen(100)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)

while True:
events = sel.select() #默认阻塞,有活动连接就返回活动的连接列表
for key, mask in events:
callback = key.data #accept
callback(key.fileobj, mask) #key.fileobj= 文件句柄

#==============================

import socket
import sys

messages = [ b‘This is the message. ‘,
b‘It will be sent ‘,
b‘in parts.‘,
]
server_address = (‘localhost‘, 9999)

# Create a TCP/IP socket
socks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(110)]
print(socks)
# Connect the socket to the port where the server is listening
print(‘connecting to %s port %s‘ % server_address)
for s in socks:
s.connect(server_address)

for message in messages:

# Send messages on both sockets
for s in socks:
print(‘%s: sending "%s"‘ % (s.getsockname(), message) )
s.send(message)

# Read responses on both sockets
for s in socks:
data = s.recv(1024)
print( ‘%s: received "%s"‘ % (s.getsockname(), data) )
if not data:
print( ‘closing socket‘, s.getsockname() )

selectors模块

标签:连接   sele   ack   range   received   connect   活动   res   net   

原文地址:https://www.cnblogs.com/rongye/p/9985475.html

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