04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

460 CHAPTER 24 ■ PROJECT 5: A VIRTUAL TEA PARTY<br />

Despite the name, it isn’t designed for the type of streaming (continuous) chat application<br />

that we’re working on. (The word “chat” in the name refers to “chat-style” or command-response<br />

protocols.) The good thing about the async_chat class (found in the asynchat module) is that it<br />

hides the most basic socket reading and writing operations: They can be a bit difficult to get<br />

right. All that’s needed to make it work is to override two methods: collect_incoming_data and<br />

found_terminator. The former is called each time a bit of text has been read from the socket,<br />

and the latter is called when a terminator is read. The terminator (in this case) is just a line<br />

break. (You’ll have to tell the async_chat object about that by calling set_terminator as part of<br />

the initialization.)<br />

An updated program, now with a ChatSession class, is shown in Listing 24-4.<br />

Listing 24-4. Server Program with ChatSession Class<br />

from asyncore import dispatcher<br />

from asynchat import async_chat<br />

import socket, asyncore<br />

PORT = 5005<br />

class ChatSession(async_chat):<br />

def __init__(self, sock):<br />

async_chat.__init__(self, sock)<br />

self.set_terminator("\r\n")<br />

self.data = []<br />

def collect_incoming_data(self, data):<br />

self.data.append(data)<br />

def found_terminator(self):<br />

line = ''.join(self.data)<br />

self.data = []<br />

# Do something with the line...<br />

print line<br />

class ChatServer(dispatcher):<br />

def __init__(self, port):<br />

dispatcher.__init__(self)<br />

self.create_socket(socket.AF_INET, socket.SOCK_STREAM)<br />

self.set_reuse_addr()<br />

self.bind(('', port))<br />

self.listen(5)<br />

self.sessions = []

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!