def conn_handler(sock): buf = [""] wait_write = [0] fd = sock.fileno() def _close(): watcher.stop() sock.close() def handle(fd): _buf = buf[0] try: _buf += sock.recv(1024) if not _buf: return _close() except socket.error as e: if e.args[0] not in NONBLOCKING: print e return _close() try: sent = sock.send(_buf) buf[0] = _buf = _buf[sent:] if _buf and not wait_write[0]: watcher.stop() watcher.fd = 1 | 2 watcher.start() wait_write[0] = 1 elif wait_write[0]: watcher.stop() watcher.fd = 1 | 2 watcher.start() wait_write[0] = 0 except socket.error as e: if e.args[0] not in NONBLOCKING: print e return _close() watcher = loop.io(sock.fileno(), 1) watcher.start(handle, fd)
def f(): s, address = sock.accept() print "join:", address cio = loop.io(s.fileno(), 1) cio.start(handler, s, cio)
import socket # 普通socket import gevent from gevent.core import loop def handler(s, cio): msg = s.recv(100) if not msg: print "left:", s.getpeername() cio.stop() s.close() else: s.send("%s\r\n" % msg) def f(): s, address = sock.accept() print "join:", address cio = loop.io(s.fileno(), 1) cio.start(handler, s, cio) loop = loop() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("localhost", 10000)) sock.listen(10) io = loop.io(sock.fileno(), 1) #1代表read io.start(f) loop.run()
def _close(self): self.watcher.stop() self._conn.close() self._conn = None def connection_ready(sock): while True: try: connection, address = sock.accept() except socket.error, e: if e[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): raise return connection.setblocking(0) #Connection(connection) conn_handler(connection) if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) sock.bind(("", 5000)) sock.listen(1024) loop.io(sock.fileno(), 1).start(connection_ready, sock) loop.run() print "exited cleanly"
print("user sock2") s, address = sock2.recvfrom(1024) else: print("user sock1") s, address = sock.recvfrom(1024) # print dir(io) # print dir(io2) # print dir(loop) # s, address = sock.accept() # print address # s.send("hello world\r\n") return f2 loop = loop() # sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind(("localhost", 9530)) # sock.listen(10) io = loop.io(sock.fileno(), 1) #1 # io.args = ('c', 'd') io.start(f('9530')) sock2 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock2.bind(("localhost", 9529)) # sock.listen(10) io2 = loop.io(sock2.fileno(), 1) #1 # io2.args = ('a', 'b') io2.start(f('9529')) loop.run()