在python中将变量存储到套接字
我有一个简单的基于 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 )
我怎样才能成功地做到这一点?
I have a simple python telnet based chat server that lacks the functionality for users to set usernames. The full script is located here: http://paste.pound-python.org/show/16076/
Basically I create my listener:
self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.srvsock.bind( ('', port ) )
self.srvsock.listen( 5 )
self.descriptors = [ self.srvsock ]
Then I use select.select to cycle through connected users and their socket sends:
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
My question is with the self.set_username method I've created, I need a way to set the username and store it inside the user socket and reference it. my set_username() method is as follows:
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 )
How can I do this successfully?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您当然可以找到某种方法来解决这个问题,但是您应该实现一个
Connection
类来处理一个客户端连接并跟踪用户名等内容,例如You can certainly find some way to hack this in, but you should implement a
Connection
class that handles one client connection and keeps track of things like the username, e.g.