Hey there
I've been following through the book "Beginning Python from Novice to Professional", and I have learned a great deal. At the moment, I am trying to expand upon the chatroom project near the end of this book.
My problem, is that I can't get my head around how to allow the users to add new rooms. At the moment, there is only one room. My first thought on how to do this was instantiating objects from the main room class, using the name that the user entered in the command. So, entering the command "/room myroom" would create a new object called "myroom" (if it didn't already exist) and then move the user into that room.
However, I can't see how you can specify the name of the new object as the program is running. A google session turned up nothing either.
I think I am attacking this in totally the wrong way, am I? - from asyncore import dispatcher
-
from asynchat import async_chat
-
-
import socket, asyncore
-
-
PORT = 5006
-
NAME = "Test Chat"
-
-
class EndSession(Exception): pass
-
-
class CommandHandler():
-
def unknown(self, session, cmd):
-
session.push('Unknown Command: %s\r\n' % cmd)
-
-
def handle(self, session, line):
-
if not line.strip(): return
-
-
parts = line.split(' ', 1)
-
cmd = parts[0]
-
#try: line = parts[1].strip()
-
#except IndexError: line = ''
-
-
if cmd[0] == "/":
-
cmd = cmd[1:]
-
meth = getattr(self, 'do_'+cmd, None)
-
-
if callable(meth):
-
meth(session, line)
-
else:
-
self.unknown(session, cmd)
-
else:
-
meth = getattr(self, 'do_say', None)
-
if callable(meth):
-
meth(session, line)
-
else:
-
self.unknown(session, cmd)
-
-
class Room(CommandHandler):
-
def __init__(self, server):
-
self.server = server
-
self.sessions = []
-
self.name = "default"
-
-
def add(self, session):
-
self.sessions.append(session)
-
-
def remove(self, session):
-
self.sessions.remove(session)
-
-
def broadcast(self, line):
-
for session in self.sessions:
-
session.push(line)
-
-
def do_logout(self, session, line):
-
raise EndSession
-
-
def do_room(self, session, line):
-
parts = line.split(' ', 1)
-
try: line = parts[1].strip()
-
except IndexError: line = ''
-
roomname = line.strip()
-
session.enter(self.server.main_room)
-
-
class LoginRoom(Room):
-
def add(self, session):
-
Room.add(self, session)
-
self.broadcast('Welcome to %s\r\n' % self.server.NAME)
-
-
def unknown(self, session, cmd):
-
session.push('Please log in \nUse "login <nick>"\r\n')
-
-
def do_login(self, session, line):
-
parts = line.split(' ', 1)
-
try: line = parts[1].strip()
-
except IndexError: line = ''
-
name = line.strip()
-
if not name:
-
session.push('Please enter a name\r\n')
-
elif name in self.server.users:
-
session.push('That name is already in use!')
-
else:
-
session.name = name
-
session.enter(self.server.main_room)
-
-
-
class ChatRoom(Room):
-
def add(self, session):
-
self.broadcast(session.name + ' has entered the room!\r\n')
-
self.server.users[session.name] = session
-
Room.add(self, session)
-
-
def remove(self, session):
-
Room.remove(self, session)
-
self.broadcast(session.name + ' has left the room!\r\n')
-
-
def do_say(self, session, line):
-
self.broadcast(session.name+': '+line+'\r\n')
-
-
def do_look(self, session, line):
-
session.push('The following people are in the room:\r\n')
-
for other in self.sessions:
-
session.push(other.name + '\r\n')
-
-
def do_who(self, session, line):
-
session.push('The following people are logged in:\r\n')
-
for name in self.server.users:
-
session.push(name + '\r\n')
-
-
class LogoutRoom(Room):
-
def add(self, session):
-
try: del self.server.users[session.name]
-
except KeyError: pass
-
-
class ChatSession(async_chat):
-
def __init__(self, server, sock):
-
async_chat.__init__(self, sock)
-
self.server = server
-
self.set_terminator("\r\n")
-
self.data = []
-
self.name = None
-
self.enter(LoginRoom(server))
-
-
def enter(self, room):
-
try: cur = self.room
-
except AttributeError: pass
-
else: cur.remove(self)
-
self.room = room
-
room.add(self)
-
-
def collect_incoming_data(self, data):
-
self.data.append(data)
-
-
def found_terminator(self):
-
line = ''.join(self.data)
-
self.data = []
-
try: self.room.handle(self, line)
-
except EndSession:
-
self.handle_close()
-
-
def handle_close(self):
-
async_chat.handle_close(self)
-
self.enter(LogoutRoom(self.server))
-
-
class ChatServer(dispatcher):
-
def __init__(self, PORT, NAME):
-
dispatcher.__init__(self)
-
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
-
self.set_reuse_addr()
-
self.bind(('', PORT))
-
self.listen(5)
-
self.NAME = NAME
-
self.users = {}
-
self.main_room = ChatRoom(self)
-
self.rooms
-
-
def handle_accept(self):
-
conn, addr = self.accept()
-
ChatSession(self, conn)
-
-
if __name__ == '__main__':
-
s = ChatServer(PORT, NAME)
-
try: asyncore.loop()
-
except KeyboardInterrupt: print
1 1814 bartonc 6,596
Recognized Expert Expert
Hey there
I've been following through the book "Beginning Python from Novice to Professional", and I have learned a great deal. At the moment, I am trying to expand upon the chatroom project near the end of this book.
My problem, is that I can't get my head around how to allow the users to add new rooms. At the moment, there is only one room. My first thought on how to do this was instantiating objects from the main room class, using the name that the user entered in the command. So, entering the command "/room myroom" would create a new object called "myroom" (if it didn't already exist) and then move the user into that room.
However, I can't see how you can specify the name of the new object as the program is running. A google session turned up nothing either.
I think I am attacking this in totally the wrong way, am I?
You can use exec() to turn strings into variable names. The trick (sometimes) is choosing which namespace to use. Go with default at first, thusly:
>>> class anObject:
... pass
...
>>> aName = "myVaribaleName "
>>> exec("%s = anObject" %(aName))
>>> myVaribaleName
<class __builtin__.anO bject at 0x02CB3A20>
>>>
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Socheat Sou |
last post by:
After a brief, but informative, discussion on Freenode's #zope
chatroom, I was advised to consult the gurus on c.l.p.
I'm working for a small company who is in desperate need to rewrite it's
15+ year old, flat-file, client-tracking database. The staff uses OSX,
while I administer the couple linux servers we have to run our website
and some internal sites. In our initial brainstorming session, we
decided to go with a Python backend...
|
by: Giovanni Bajo |
last post by:
Hello,
I just read this mail by Brett Cannon:
http://mail.python.org/pipermail/python-dev/2006-October/069139.html
where the "PSF infrastracture committee", after weeks of evaluation, recommends
using a non open source tracker (called JIRA - never heard before of course)
for Python itself.
Does this smell "Bitkeeper fiasco" to anyone else than me?
--
|
by: John Nagle |
last post by:
The major complaint I have about Python is that the packages
which connect it to other software components all seem to have
serious problems. As long as you don't need to talk to anything
outside the Python world, you're fine. But once you do, things
go downhill. MySQLdb has version and platform compatibility
problems. So does M2Crypto. The built-in SSL support is weak.
Even basic sockets don't quite work right; the socket module...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |