Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CMD Module with a Socket

Tags:

python

I've been having a hard time getting the CMD module to use a socket for stdin. Here is what I have :

class Server(cmd.Cmd):
    use_rawinput = False 

    def __init__(self, port): 
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.bind(("", port))
        f = self.sock.makefile(mode='rw') 
        cmd.Cmd.__init__(self, stdin = f, stdout=sys.stdout) 


    def do_register(self, username):    
        print username

When I connect with the client and try the command register user1, I don't get anything on the server's console.

like image 611
Seshu Yamajala Avatar asked Aug 16 '26 00:08

Seshu Yamajala


1 Answers

The file returned by makefile will only work for SOCK_STREAM sockets. SOCK_DGRAM sockets have no notion of a continuous stream of bytes (only individual packets), and therefore cannot use read or write.

You should initialize the socket with socket.SOCK_STREAM instead of socket.SOCK_DGRAM.

like image 132
nneonneo Avatar answered Aug 17 '26 15:08

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!