-
-
Save briehanlombaard/ba73be9fae7c0c53a136bdae08661a88 to your computer and use it in GitHub Desktop.
Basic select loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import queue | |
import select | |
import socket | |
import threading | |
import time | |
Q = queue.Queue() | |
def loop(s): | |
while True: | |
rlist, wlist, elist = select.select([s], [s], [s]) | |
# Read from sockets that are readable. | |
for rsock in rlist: | |
data = rsock.recv(1024).strip() | |
if data: | |
print(data) | |
# Write to sockets that are writeable. | |
for wsock in wlist: | |
try: | |
msg = Q.get_nowait() | |
except queue.Empty: | |
pass | |
else: | |
wsock.sendall(msg.encode()) | |
# Close sockets in error. | |
for esock in elist: | |
esock.close() | |
time.sleep(0.01) | |
s = socket.create_connection(('www.google.com', 80)) | |
s.setblocking(0) | |
t = threading.Thread(target=loop, args=(s,)) | |
t.setDaemon(True) | |
t.start() | |
Q.join() | |
while True: | |
try: | |
msg = input('') | |
except KeyboardInterrupt: | |
break | |
Q.put(msg + '\r\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment