I want a functionality to check if data is waiting in the socket to be read before reading it. Something like this would be helpful:
if (data available) then read data
else wait in blocking mode till data becomes available
How can I achieve this in Python
The python socket howto says send() will return 0 bytes written if channel is closed. You may use a non-blocking or a timeout socket. send() and if it returns 0 you can no longer send data on that socket.
sendall is a high-level Python-only method that sends the entire buffer you pass or throws an exception. It does that by calling socket. send until everything has been sent or an error occurs.
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
#incoming message from remote server
if sock == s:
data = sock.recv(4096)
if not data :
print '\nDisconnected from server'
sys.exit()
else :
#print data
sys.stdout.write(data)
#user entered a message
else :
msg = sys.stdin.readline()
s.send(msg)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With