def run(): sel = selectors.DefaultSelector() def accept(sock, mask): conn, addr = sock.accept() # Should be ready print('accepted', conn, 'from', addr) conn.setblocking(False) sel.register(conn, selectors.EVENT_READ, read) def read(conn, mask): data = conn.recv(1024) # Should be ready if data: print('echoing', repr(data), 'to', conn) conn.send(response) # Hope it won't block else: print('closing', conn) sel.unregister(conn) conn.close() sock = socket.socket() sock.bind(('localhost', 1235)) 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 callback(key.fileobj, mask)
#!/usr/bin/python3 from __future__ import print_function import sys, socket, time, mido import selectors34 as selectors sys.path.append("../core") from message import Message sel = selectors.DefaultSelector() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", 55942)) sock.setblocking(False) sel.register(sock, selectors.EVENT_READ, data=None) buf = "" port = mido.open_input("Midi Through Port-0") while True: events = sel.select(timeout=0) for key, mask in events: data = sock.recv(1024) if data is None: print("disconnected") sys.exit() else: buf += data.decode("utf-8") while "\0" in buf: idx = buf.find("\0") data = buf[0:idx] buf = buf[idx + 1:]