我有一个简单的基于python telnet的聊天服务器,它缺乏用户设置用户名的功能。完整脚本位于此处:http://paste.pound-python.org/show/16076/
基本上我创建了我的听众:
self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.srvsock.bind( ('', port ) )
self.srvsock.listen( 5 )
self.descriptors = [ self.srvsock ]
然后我使用select.select循环连接用户,他们的套接字发送:
def run( self ):
while 1:
( sread, swrite, sexec ) = select.select( self.descriptors, [], [] )
for sock in sread:
if sock == self.srvsock:
self.accept_new_connection()
else:
str = sock.recv( 6042 )
host, port = sock.getpeername()
if str == '':
#stop user connect
elif '\username' in str:
self.set_username( str, sock, port )
else:
#send user string
我的问题是我创建的self.set_username方法,我需要一种方法来设置用户名并将其存储在用户套接字中并引用它。我的set_username()方法如下:
def set_username( self, str, sock, port ):
username = str[ str.find(' ')+1: ]
sock.append( {'username': username} ) #<!!!--obviously this does not work
str = "[user:%s] now known as %s" % ( port, username )
sock.send( str )
self.broadcast_string( str )
我怎样才能成功完成这项工作?
答案 0 :(得分:2)
你当然可以找到一些方法来破解它,但你应实现一个Connection
类来处理一个客户端连接并跟踪用户名等内容,例如
class Connection(object):
def __init__(self, sock):
self.socket = sock
def fileno(self):
return self.socket.fileno()