简体   繁体   中英

store variable to socket in python

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?

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, eg

class Connection(object):
    def __init__(self, sock):
        self.socket = sock

    def fileno(self):
        return self.socket.fileno()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM