views:

391

answers:

3

Hello!

I was trying to find examples about socket programming and came upon this script: http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py

When reading through this script i found this line: listenSocket.listen(5)

As i understand it - it reads 5 bytes from the buffer and then does stuff with it...

but what happens if more than 5 bytes were sent by the other end?

in the other place of that script it checks input against 4 commands and sees if there is \r\n in the string. dont commands like "look" plus \r\n make up for more than 5 bytes?

Alan

+9  A: 

It seems you got it wrong.

socket.listen() is used on a server socket to listen for incoming connection requests.

The parameter to listen is called the backlog and it means how many connections should the socket accept and put in a pending buffer until you finish your call to accept(). That applies to connections that are waiting to connect to your server socket between the time you have called listen() and the time you have finished a matching call to accept().

So, in your example you're setting the backlog to 5 connections.

Note.. if you set your backlog to 5 connections, the following connections (6th, 7th etc.) will be dropped and the connecting socket will receive an error connecting message (something like a "host actively refused the connection" message)

Miky Dinescu
Correct - see the documentation for details: http://docs.python.org/library/socket.html#socket.socket.listen
mark4o
Thanks. I understood it wrong indeed, but from the same link, above... socket.recv(bufsize[, flags])What happens to other sent bytes in the buffer and how to make sure all relevat info was read from the buffer?
Zayatzz
If there are more bytes then they will remain in the receive buffer. Call recv again to read more. In your example program it calls recv(1000) so it will read up to 1000 bytes (less if there are not that many available).
mark4o
Well since i dont know how many bytes are in the buffer and i would like to read exactly as much is necessary i dont know if just reading more is the solution. Is it for example possible untill certain string like \r\n ?
Zayatzz
It sounds like you want a file object, not a low-level socket. Use socket.makefile - example here: http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf
mark4o
A: 

This might help you understand the code: http://www.amk.ca/python/howto/sockets/

Zed
A: 

The argument 5 to listenSocket.listen isn't the number of bytes to read or buffer, it's the backlog:

socket.listen(backlog)

Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

Jared Oberhaus