Created
February 10, 2015 10:52
-
-
Save eguven/48334384dc528e9b426a to your computer and use it in GitHub Desktop.
asyncore echo
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 asyncore | |
import socket | |
import sys | |
class EchoHandler(asyncore.dispatcher_with_send): | |
def handle_read(self): | |
data = self.recv(8192) | |
if data: | |
self.send(data) | |
class EchoServer(asyncore.dispatcher): | |
def __init__(self, host, port): | |
asyncore.dispatcher.__init__(self) | |
self.create_socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.set_reuse_addr() | |
self.bind((host, port)) | |
self.listen(5) | |
def handle_accept(self): | |
pair = self.accept() | |
if pair is not None: | |
sock, addr = pair | |
print 'Incoming connection from %s' % repr(addr) | |
handler = EchoHandler(sock) | |
if __name__ == '__main__': | |
host = sys.argv[1] if len(sys.argv) >= 2 else '127.0.0.1' | |
port = int(sys.argv[2]) if len(sys.argv) == 3 else 8080 | |
server = EchoServer(host, port) | |
asyncore.loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment