#! usr/bin/env python
#import modules...
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
from elementtree.ElementTree import *
import ConfigParser
import time
#load the host and port from a ini file
config = ConfigParser.ConfigParser()
config.read("settings.ini")
port = int(config.get("server", "port"))
#The umm, server script.
class ChatServer(LineReceiver):
userlist = []
#Yay! found a new connection. Add the new user to the userlist
def connectionMade(self):
self.transport.userid = len(self.userlist)
self.transport.room = "Lobby"
self.transport.username = ""
self.userlist.append(self.transport)
print "New connection! ID = %s IP = %s" % (self.transport.userid, self.transport.getHost())
#receive the messages and send them
def lineReceived(self, line):
print line
#convert the xml code to an element
element = fromstring(line)
#get some variables from the element
thetime = element.findtext("time")
nick = element.findtext("nick")
msg = element.findtext("msg")
type = element.findtext("type")
room = element.findtext("room")
newnick = element.findtext("newnick")
oldnick = element.findtext("oldnick")
#convert the element to a string
string = tostring(element)
# send the message in various formats ###
#normal type of sending
if type is "normal" or type is "notice":
self.send(string, 'room')
#new user! add his nickname to the userlist
elif type == "newuser":
self.userlist[len(self.userlist)-1].username = nick
self.userlist[len(self.userlist)-1].room = room
self.send_list_of_usernames()
self.send(string, "room")
#user changed his nick. update the userlist.
elif type == "newnick":
for user in self.userlist:
if user.username == oldnick:
user.username = newnick
self.send_list_of_usernames()
self.send(string, "room")
#sends the list of usernames to the clients
def send_list_of_usernames(self):
#convert to xml format
element = Element("list")
SubElement(element, "type").text = "users"
for user in self.userlist:
if user.room == self.transport.room:
SubElement(element, "user").text = user.username
#convert element to string
string = tostring(element)
#send the string of xml code
self.send(string, "room")
#script for sending messages to rooms
def send(self, message, where):
#all the users connected to the server
def all():
for user in self.userlist:
user.write(message + "\r\n\r\n")
#only the room it came from
def room():
for user in self.userlist:
if user.room == self.transport.room:
user.write(message + "\r\n\r\n")
#only to the user it came from
def myself():
self.transport.write(message + "\r\n\r\n")
{'all': all,
'room': room,
'myself': myself}[where]()
#lose a connection, remove the user from the userlist
def connectionLost(self, reason):
self.userlist.remove(self.transport)
self.send_list_of_usernames()
print "Lost connection, %s" % (reason)
#lets run
factory = Factory()
factory.protocol = ChatServer
#listen on the port provided
reactor.listenTCP(port, factory)
reactor.run()