转于http://my.oschina.net/u/1433482/blog/190696
#coding:utf-8
#最好用twisted进行异步I/O编程
#客户端
import asyncoreimport socketclass 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)server = EchoServer('localhost', 8080)asyncore.loop()
#服务器
import asyncoreimport socketclass 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)server = EchoServer('localhost', 8080)asyncore.loop()