Skip to content

Instantly share code, notes, and snippets.

@jart
Created April 12, 2010 19:45
Show Gist options
  • Save jart/363925 to your computer and use it in GitHub Desktop.
Save jart/363925 to your computer and use it in GitHub Desktop.
import select
import socket
class UDPEchoServer(object):
def __init__(self):
self.sock = socket.socket(type=socket.SOCK_DGRAM)
self.sock.bind(('0.0.0.0', 5000))
def fileno(self):
return self.sock.fileno()
def do_stuff(self):
data, addr = self.sock.recvfrom(4096)
self.sock.sendto(data, addr)
class TCPEchoServer(object):
def __init__(self):
self.sock = socket.socket()
self.sock.bind(('0.0.0.0', 5000))
self.sock.listen(5)
def fileno(self):
return self.sock.fileno()
def do_stuff(self):
sock, addr = self.sock.accept()
client = TCPEchoClient(sock, addr)
FILE_OBJECTS.append(client)
class TCPEchoClient(object):
def __init__(self, sock, addr):
self.sock = sock
def fileno(self):
return self.sock.fileno()
def do_stuff(self):
data = self.sock.recv(4096)
if data:
self.sock.send(data)
else:
FILE_OBJECTS.remove(self)
if __name__ == '__main__':
FILE_OBJECTS = [UDPEchoServer(), TCPEchoServer()]
print "Ready <3"
print "Try running: telnet localhost 5000"
while True:
rfds, wfds, xfds = select.select(FILE_OBJECTS, [], FILE_OBJECTS)
for f in rfds + xfds:
f.do_stuff()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment