Created
December 25, 2011 11:32
-
-
Save sonkm3/1519116 to your computer and use it in GitHub Desktop.
python 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 | |
class EchoHandler(asyncore.dispatcher): | |
def __init__(self, sock): | |
asyncore.dispatcher.__init__(self, sock=sock) | |
self.send('welcome') | |
return | |
def handle_read(self): | |
data = self.recv(8192) | |
if data: | |
if data.rstrip("\r\n") == '': | |
self.send('disconnect') | |
self.close() | |
self.send(data) | |
class Server(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(1) | |
def handle_accept(self): | |
pair = self.accept() | |
if pair: | |
sock, addr = pair | |
handler = EchoHandler(sock) | |
server = Server('localhost', 8080) | |
while asyncore.socket_map: | |
asyncore.loop(timeout=1, count=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment