# -*- coding: utf-8 -*- # 斌彬电脑 # @Time : 2018/7/12 0012 20:29 import socket server = socket.socket() server.setblocking(False) server.bind(('',10000)) # 绑定ip,和端口, server.listen(5) con_l = [] while 1: try: con,addr = server.accept() con.setblocking(False) con_l.append(con) except Exception: pass del_l = [con for con in con_l] for con in con_l: try: recv_data = con.recv(1024) if recv_data: print(recv_data) con.send(recv_data) else: con.close() con_l.remove(con) except Exception: pass
# -*- coding: utf-8 -*- # 斌彬电脑 # @Time : 2018/7/13 0013 23:16 import socket,selectors import tuling epoll_secret = selectors.DefaultSelector() #根据平台选择最佳的IO多路机制,比如linux就会选择epoll sever = socket.socket() sever.bind(('',10000)) sever.listen(1000) def read(conn): try: rec_data = conn.recv(1024) # if rec_data: # 在 linux 中 print(rec_data.decode('utf-8')) se = tuling.Tuling(rec_data.decode('utf-8')) conn.send(se.encode('utf-8')) except Exception: # else: epoll_secret.unregister(conn) # 如果客户端断开,就取消对应的注册事件 def accept(sever): conn,addr = sever.accept() print('客户端地址:', addr) # 处理事件 epoll_secret.register( conn, selectors.EVENT_READ, read ) # return conn # 注册事件 epoll_secret.register( sever, selectors.EVENT_READ, accept ) # 3 个参数: 监听套接字, 可读, 回调函数 # 事件说明:当监听到有活跃客户端(可读)发生时,运行指定函数 while True: # 开启事件 # 循环查询客户端事件,把连接的客户端写入列表 , events = epoll_secret.select() # print(events) # # [(SelectorKey(fileobj=<socket.socket fd=608, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 9002)>, fd=608, events=1, data=<function accept at 0x000001A04AEE6A60>), 1)] # events[0] 中有监听套接字,accept 的函数 for key,m in events: sock = key.fileobj # 获取 对等连接套接字 callback = key.data # 获取 accept callback( sock ) # == def accept(ser) 的调用