question...

Peter Hansen peter at engcorp.com
Fri Aug 24 07:22:11 CEST 2001


Adonis Vargas wrote:
> 
> how am i able to read a socket.recv() line by line instead of receving
> it all bunched up? i have looked into the socket documentation and have
> come up with makefile(); but how would i use it? is it the same as if i
> were handling an open() statement? or something completely different?

According to the docs, you are correct.  open() returns a file object,
and makefile() says it does the same.  That means the following
(untested) code should work (where host is an IP address as a string,
e.g. '192.168.0.1'):

def getLinesFromServer(host, port):
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    file = s.makefile('r')
    return file.readlines()

(I'd forgotten about this socket function.  Thanks for reminding me. :)

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list