Created
June 6, 2014 16:33
-
-
Save thomasballinger/f57160c656a332a31e6f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import termios, fcntl, sys, os, select, socket, threading, time | |
fd = sys.stdin.fileno() | |
oldterm = termios.tcgetattr(fd) | |
newattr = oldterm[:] | |
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO | |
termios.tcsetattr(fd, termios.TCSANOW, newattr) | |
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) | |
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) | |
try: | |
server = socket.socket() | |
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
server.bind(('', 2000)) | |
server.listen(5) | |
time.sleep(.5) | |
client = socket.socket() | |
client.connect(('', 2000)) | |
t = threading.Thread(target=lambda: [time.sleep(1), [(time.sleep(1), client.send('hey there!')) for _ in xrange(1000)]]) | |
t.daemon = True | |
t.start() | |
s, (ip, port) = server.accept() | |
print 'connection from %r:%r' % (ip, port) | |
while 1: | |
rs, ws, es = select.select([fd, s], [], []) | |
for r in rs: | |
if r == sys.stdin.fileno(): | |
c = os.read(r, 1024) | |
print "Got characters", repr(c) | |
if c == "q": | |
break # quit | |
if r is s: | |
print "Got msg on socket", repr(s.recv(1024)) | |
finally: | |
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) | |
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
based on http://effbot.org/pyfaq/how-do-i-get-a-single-keypress-at-a-time.htm