Simple chat server using Atlas-Python
What it does
It accepts login and create operations and records ids given by the client. Then everything the user says is broadcast to every client.
Code
Server class
Keeps track of currently connected clients and sends the requested talk operation, inside a sound operation, to all clients
"send_all" -sends the requested talk operation as a sound perception to all clients that have logged in.
"has_account" -used to check whether a client with the given id already exists.
class ChatServer(server.SocketServer):
def send_all(self, op):
for client in self.clients:
if hasattr(client, "id"):
client.sendoperation(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 a client with the requested id already exists, sends an error operation.
Talk operations are simply forwarded to the server part to be broadcasted to every client. If the client is not logged in, then talk operations are discarded.
create_op = login_op
def talkop(self, op): if hasattr(self, "id"): op.from = self.id self.server.send_all(op)
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))
Main part
Here we create the server instance, giving it ChatClient as an argument to
use when creating new connections, and then go into the processing loop:
s = ChatServer("Simple OOG chat server", server.args2address(sys.argv),
ChatClient)
s.loop()
For the 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: Sat Sep 1 15:30:40 EEST 2001
| Current Issue: February 2003, Recent Issues: January 2003, November 2002, October 2002 |