reading from sockets

Simon Forman rogue_pedro at yahoo.com
Thu Aug 10 15:02:45 EDT 2006


AndrewTK wrote:
> Hello,
>
> I'm trying to read data from a socket and I'm not seeing what I'm
> expecting.... it seems to skip the first line of data. I am new to
> Python and just trying to test what I can do with it... and it's not
> looking pretty.
>
>
> I have some Python code:
> [------------------------------
> #! /usr/bin/python
>
> import socket
>
> s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
> s.connect( ("localhost",54321) );
> s.send("hello")
> data = s.recv(1024)
> while len(data) > 0:
> 	print repr(data) # the first print of data always seems to "ignore"
> the first line of data...
> 	data = s.recv(1024)
> ------------------------------]
>
> On localhost 54321 I have a server (in Java) writing out
>
> [------------------------------
> first
> second
> third
> <EOF>
> ------------------------------]
> (on EOF, the stream is simply closed.)
>
> The result of the script is to print
>
> [------------------------------
> second
> third
> ------------------------------]
>
> I have tried already
> [++++++++++++++
> data = " "
> while len(data) > 0:
> 	data = s.recv(1024)
> 	print repr(data)
> ++++++++++++++]
>
> but that has not changed anything. The first line to come through is
> always skipped it would seem.
>
> Any ideas as to why that would be....? I was thinking scope when I made
> the last example, but apparently that is not the case.
>
> Andrew

Hmm..  that's very very strange.

Try putting "print repr(data)" immediately before your while statement
and after the first recv() call to see...   well, actually, nevermind
that.

Double check that the first line really is being sent (with netcat or
telnet or something.) That's the only thing I can think of, your code
should be working..  If the first line is really being sent, but not
arriving in your code, you've got something strange going on.

(BTW, "while len(data) > 0:" can just be "while data:")

(Heaven help me, but maybe you could post your java server code here...
 If anyone screams too loudly blame me. Hahaha..)

Peace,
~Simon




More information about the Python-list mailing list