Ichabod Crane
Ichabod Crane

Reputation: 127

Socket makefile() not responding the second time I call it

I am trying to learn how to use socket.makefile() function, but I am stuck at getting the second response from a server Here is my test code

import socket
S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
S.connect(('smtp.comcast.net',25))
file = S.makefile('rwb')
line = file.readlines()
print repr(line)
file.write("Ehlo User\r\n")
line = file.readlines()
print repr(line)

And here is what I receive when I run it:

['220 omta06.emeryville.ca.mail.comcast.net comcast ESMTP server ready\r\n']
[]

What am I doing wrong here? I googled alot of results, seems there isn't much documentation over the makefile() function. Any help would be much appreciated.

Upvotes: 0

Views: 890

Answers (1)

Robᵩ
Robᵩ

Reputation: 168866

The first call to .readlines() reads all of the lines and doesn't return until it has read every single line that will ever be available. When .readlines() is called again, there are no more lines to read. Perhaps you should call .readline() instead.

Oh, and by the way, don't name your variables after built-in types. It isn't invalid, but it is bad practice.

Try this:

import socket
S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
S.connect(('smtp.comcast.net',25))
server = S.makefile('rwb')
line = server.readline()
print repr(line)
server.write("Ehlo User\r\n")
line = server.readline()
print repr(line)

Upvotes: 2

Related Questions