server:
#!_*_coding:utf-8_*_ #__author__:"Alex huang" import selectors #selector模块集成了select,epoll,优先使用epoll,如果系统支持,windows不支持epoll import socket def accept(s,mask): #这个回调函数实现建立N个并发连接 conn,addr = s.accept() print("established to ",addr) conn.setblocking(False) sel.register(conn,selectors.EVENT_READ,handle) #将连接加入selector并回调handle def handle(conn,mask): #要实现的功能写在这个回调函数内 data = conn.recv(1024) if data: print("recv:",data.decode()) re_data = data.decode().upper() conn.send(re_data.encode()) else: print("closed conn...") sel.unregister(conn) #关闭连接 conn.close() sel = selectors.DefaultSelector() s = socket.socket() s.bind(("0.0.0.0",5000)) s.listen(5) sel.register(s,selectors.EVENT_READ,accept) #第一次回调accept,s是传给执行函数accept的参数 while True: events = sel.select() #默认阻塞,有连接时就返回活动的连接列表 for key,mask in events: callback = key.data callback(key.fileobj,mask)
client:
#!/usr/bin/env python # -*- coding: utf-8 -*- # author aliex-hrg __author__ = "alex" import socket import sys messages = [ 'This is the message. ', 'It will be sent ', 'in parts.', 'the end of' ] server_address = ('192.168.80.100', 5000) # Create a TCP/IP socket socks = [ socket.socket(socket.AF_INET, socket.SOCK_STREAM) for i in range(10000) ] #模拟10000个会话 # 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.encode()) # Read responses on both sockets for s in socks: data = s.recv(1024) print( '%s: received "%s"' % (s.getsockname(), data) ) if not data: print(sys.stderr, 'closing socket', s.getsockname() )
...