Simple chat server using Atlas-Python

What it does

It accepts login and create operations and records id given by client. Then everything user talks is broadcast to every client.

Code

Server class

Keeps track of currently connected clients and sends to all clients requested talk operation inside sound operation.

"send_all" -method sends to all clients that have already logged in requested talk operation as sound perception.

"has_account" -method is used to check whether there already exists client with given id.

class ChatServer(server.SocketServer):
    def send_all(self, op):
        for client in self.clients:
            if hasattr(client, "id"):
                client.send_operation(atlas.Operation("sound",
                                                      op,
                                                      from_ = op.from_,
                                                      to = client.id))
    def has_account(self, id):
        for client in self.clients:
            if hasattr(client, "id") and client.id == id:
                return 1
        return 0

Client class

Handles login/create operations and sets id to requested account id. If client with requested id already exists, sends error operation.

Talk operations are simply forwarded to server part to be broadcasted to every client. If client is not logged in, then talk operation is discarded.

class ChatClient(server.TcpClient):
    def login_op(self, op):
        account = op.args[0].id
        if self.server.has_account(account):
            self.send_error(op, "somebody already in with that id")
        else:
            self.id = account
            ent = atlas.Object(parents=["player"], id=account)
            self.reply_operation(op, atlas.Operation("info",
                                                     ent,
                                                     to=account))

    create_op = login_op

    def talk_op(self, op):
        if hasattr(self, "id"):
            op.from_ = self.id
            self.server.send_all(op)

Main part

Here we create server instance giving it ChatClient as argument to use when creating new connections and then go into processing loop:
    s = ChatServer("Simple OOG chat server", server.args2address(sys.argv), ChatClient)
    s.loop()

For whole example code see forge/libs/Atlas-Python/chat_server.py

Example telnet sessions

To test chat_server.py from telnet, paste these into telnet sessions:

Session1:

ATLAS telnet client
ICAN Bach_beta

{parents:["login"], args:[{id:"al"}], id:"0", objtype:"op"}
{parents:["talk"], args:[{say:"Hello world!"}], from:"al", objtype:"op"}
Session2:
ATLAS telnet client
ICAN Bach_beta

{parents:["login"], args:[{id:"la"}], id:"0", objtype:"op"}
{parents:["talk"], args:[{say:"!dlrow olleH"}], from:"la", objtype:"op"}

Aloril
Last modified: Thu Sep 6 07:00:23 EEST 2001