Last active
May 28, 2017 09:44
-
-
Save yingshaoxo/a11117ecaa1d1136182b8eddc501c8e7 to your computer and use it in GitHub Desktop.
asyncore TCP server
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
import asyncore | |
connected_sockets = dict() | |
class SocketHandler(asyncore.dispatcher_with_send): | |
def handle_read(self): | |
data = self.recv(8192) | |
#print(connected_sockets) | |
if data: | |
for i in [i for i in connected_sockets.values() if i != self.socket]: | |
i.send(data) | |
print("Now I got", len(connected_sockets.keys()), "connections.") | |
def handle_close(self): | |
del connected_sockets[self.addr] | |
self.close() | |
class SocketServer(asyncore.dispatcher): | |
def __init__(self, host, port): | |
asyncore.dispatcher.__init__(self) | |
self.create_socket() | |
self.set_reuse_addr() | |
self.bind((host, port)) | |
self.listen(5) | |
def handle_accepted(self, sock, addr): | |
#print('Incoming connection from %s' % repr(addr)) | |
connected_sockets.update({addr: sock}) | |
handler = SocketHandler(sock) | |
socket_server = SocketServer('127.0.0.1', 5920) | |
asyncore.loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment