Socket and cycle problem

Jean-Paul Calderone exarkun at divmod.com
Mon May 12 11:54:47 EDT 2008


On Mon, 12 May 2008 08:34:07 -0700 (PDT), petr.poupa at gmail.com wrote:
>Hello,
>I am beginner but so I need help. I have small script for receive data
>from port 3883, but it print only once.
>
>import socket
>
>HOST = 'localhost'
>PORT = 3883
>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>s.connect((HOST, PORT))
>data = s.recv(2048)
>s.close()
>print 'receive data from server:', `data`
>
>So I try to write cycle to this script, like this:
>
>import socket
>
>HOST = 'localhost'
>PORT = 3883
>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>while 1:
>    s.connect((HOST, PORT))
>    data = s.recv(2048)
>    s.close()
>    print 'receive data from server:', `data`
>
>But Python reporting:
>
>Traceback (most recent call last):
>  File "C:\Documents and Settings\poupa\Plocha\TCP3.py", line 7, in
><module>
>    s.connect((HOST, PORT))
>  File "<string>", line 1, in connect
>  File "C:\Python25\lib\socket.py", line 141, in _dummy
>    raise error(EBADF, 'Bad file descriptor')
>error: (9, 'Bad file descriptor')
>
>Where is the mistake? I dont know.

You cannot reconnect a socket.  You need to create a new one for each
connection.  It's also almost certainly the case that the way you are
receiving data is incorrect.  There is no guarantee that you will get
2048 bytes from socket.recv(2048).  It isn't even guaranteed that all
the bytes written to the socket by the peer will be returned by such
a call.  Instead, you need a framing protocol to determine when all
data has been received.  For example, you might length prefix the
data, or you might insert a delimiter (or a terminator) at the end.  Or
if there is exactly one message to receive, then you should just read
until the recv call returns '', indicating EOF.

Jean-Paul



More information about the Python-list mailing list