socket issue with recv()
Arthur Clarck
aclarck5 at gmail.com
Sat Aug 23 04:23:14 EDT 2014
Hello,
I am starting socket scripting with python.
I do understand from the doc that a socket is bmocking by default.
I wrote 2 basics script to verify this behaviour.
my "tcp_server.py":
import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.0.103'
PORT = 1060
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
while True:
s.listen(1)
print 'Listening at', s.getsockname()
sc, sockname = s.accept()
print 'We have accepted a connection from', sockname
print 'Socket connects', sc.getsockname(), 'and', sc.getpeername()
while True:
data = sc.recv(1024)
if data:
print 'Got from client:', repr(data)
data = ''
else:
#raise EOFError('socket closed')
print 'socket closed by remote client'
sc.close()
sys.exit()
and my "tcp_client.py"
import socket, sys, time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.0.103'
PORT = 1060
s.connect((HOST, PORT))
print 'Client has been assigned socket name', s.getsockname()
while True:
data = raw_input('cmd:')
if (data == '\x05'):
print 'closing socket and exit'
s.close()
sys.exit()
s.sendall(data)
When both are running everything what I type in the client is received by the server.
When nothing is sent from the client the server is waiting (socket is blocking)
for next datas.
If I close the client with Ctrl-E (or a kill) the socket on the server is getting a null value and the server exit.
So everything is fine. And everything is clear in my mind.
The problem I have now is the following.
I have a script to connect to some telecom service.
The script is forking (parent/child)
The child is only reading what comes from the remote server.
Here the problematic code:
total = ''
while True:
data = s.recv(1024)
total += data
if (data == ''):
print 'remote site is closed'
s.close()
sys.exit()
What is happening is that I got some datas from the remote site,
Something like 'Contacting BH: ...'
But directly followed by 'remote site is closed.
And if I remove the 2 lines (s.close;sys.exit) my script is looping
So it means data==''
This makes no sense at all.
Why is the socket not waiting for the next datas flow ??
Why is the socket not blocking ?
With Perl I just have to write:
while (sysread($socket,$data,1024)){
syswrite(STDOUT,$data)
}
And it works perfectly.
Any hint about what I missed in Python ?
kr,
Arthur.
More information about the Python-list
mailing list