简单聊天室

concurrence examples
#server
#chat.py
from concurrence import dispatch, Tasklet, Message
from concurrence.io import BufferedStream, Socket, Server

class MSG_WRITE_LINE(Message): pass
class MSG_QUIT(Message): pass
class MSG_LINE_READ(Message): pass

connected_clients = set() #set of currently connected clients (tasks)
        
def handle(client_socket):
    """handles a single client connected to the chat server"""
    stream = BufferedStream(client_socket)

    client_task = Tasklet.current() #this is the current task as started by server
    connected_clients.add(client_task)
    
    def writer():
        for msg, args, kwargs in Tasklet.receive():
            if msg.match(MSG_WRITE_LINE):
                stream.writer.write_bytes(args[0] + '\n')
                stream.writer.flush()
            
    def reader():
        for line in stream.reader.read_lines():
            line = line.strip()
            if line == 'quit': 
                MSG_QUIT.send(client_task)()
            else:
                MSG_LINE_READ.send(client_task)(line)
    
    reader_task = Tasklet.new(reader)()
    writer_task = Tasklet.new(writer)()

    MSG_WRITE_LINE.send(writer_task)("type 'quit' to exit..")
    
    for msg, args, kwargs in Tasklet.receive():
        print args[0]
        if msg.match(MSG_QUIT):
            break
        elif msg.match(MSG_LINE_READ):
            #a line was recv from our client, multicast it to the other clients
            for task in connected_clients:
                if task != client_task: #don't echo the line back to myself
                    MSG_WRITE_LINE.send(task)(args[0])
        elif msg.match(MSG_WRITE_LINE):
            MSG_WRITE_LINE.send(writer_task)(args[0])
        
    connected_clients.remove(client_task)
    reader_task.kill()
    writer_task.kill()
    client_socket.close()
           
def server():
    """accepts connections on a socket, and dispatches
    new tasks for handling the incoming requests"""
    print 'listening for connections on port 9010'
    Server.serve(('localhost', 9010), handle)

if __name__ == '__main__':
    dispatch(server)

#client
#client.py
# coding: UTF8

from concurrence.core import dispatch, Message, Tasklet
from concurrence.io.buffered import BufferedStream
from concurrence.io.socket import Socket

class MSG_SEND(Message): pass
class MSG_QUIT(Message): pass
class MSG_LINE_READ(Message): pass

def client():
    client_task = Tasklet.current()
    client_id = id(client_task)
    
    sock = Socket.connect(("localhost", 9010), 5)
    stream = BufferedStream(sock)
   
    def writer():
        for msg, args, _ in Tasklet.receive():
            try:
                if msg.match(MSG_SEND):
                    data = args[0]
                    
                    print "SEND:", data
                    stream.writer.write_bytes(data + '\n')
                    stream.writer.flush()
            except Exception, e:
                print "WREX:", e
                break
        MSG_QUIT.send(client_task)()
            
    def reader():
        while True:
            try:
                for line in stream.reader.read_lines():
                    line = line.strip()
                    MSG_LINE_READ.send(client_task)(line)
            except Exception, e:
                print "RDEX:", e
                break
        MSG_QUIT.send(client_task)()
        
    reader_task = Tasklet.new(reader)()
    writer_task = Tasklet.new(writer)()
    
    def send(data):
        MSG_SEND.send(client_task)(data)
        
    def process(data):
        print "RECV:", data
        
    def play_game():
        while True:
            send("hello")
            Tasklet.sleep(5)
                
    Tasklet.later(3, play_game)()

    for msg, args, _ in Tasklet.receive():
        if msg.match(MSG_LINE_READ):
            process(args[0])
        elif msg.match(MSG_SEND):
            MSG_SEND.send(writer_task)(args[0])
    
    print "close"
    reader_task.kill()
    writer_task.kill()
    sock.close()

if __name__ == '__main__':
    dispatch(client)

猜你喜欢

转载自ghh0000.iteye.com/blog/1695086