One more question : I shall sue the same archietcture for my client I suppose. In this case what shall i use instead of
self.create_socket(…)
?
Thanx
Robert
Josiah Carlson jcarlson@uci.edu a écrit :
···
At the end of this message is an implementation of an echo server. It
requires a couple small changes in the wiki entry, and it won’t be the
fastest, but it should work (unless I made a mistake).
- Josiah
from cStringIO import StringIO
import cPickle
import struct
import asynchatclass DispatcherConnection(asynchat.async_chat):
def init(self, connection, mainwindow):
self.mainwindow = mainwindow
asynchat.async_chat.init(self, connection)
self.state = 0
self.set_terminator(4)
self.received =
cStringIO()
def push(self, structure):
ds = cPickle.dumps(structure)
#we use network-endian byte order
ds = struct.pack(‘>L’, len(ds)) + ds
asynchat.async_chat.push(ds)
def log(self, message):
self.mainwindow.LogString(message, sock=self)
def log_info(self, message, type=‘info’):
if type != ‘info’:
self.log(message)
def handle_close(self):
self.log(“Connection dropped: %s”%(self.addr,))
self.close()
def collect_incoming_data(self, data):
self.received.write(data)
def found_terminator(self):
self.state = not self.state
if self.state:
self.received.seek(0)
self.set_terminator(struct.unpack(‘>L’, self.received.read(4))[0])
self.received.clear()
else:
self.received.seek(0)
data = cPickle.load(self.received)self.set_terminator(4) self.received.clear() self.handle_data(data) #implement your client logic as a subclass by overriding handle_data def handle_data(self, data): raise NotImplemented
class EchoConnection(DispatcherConnection):
def handle_data(self, data):
self.log(‘got data: %r’%(data,))
Découvrez une nouvelle façon d’obtenir des réponses à toutes vos questions ! Profitez des connaissances, des opinions et des expériences des internautes sur Yahoo! Questions/Réponses.