Reputation: 4370
I'm using this method to send data from a Java client and receiving it on a python server. The data sent is a simple string of length 10 but I'm not able to receive it on server side. It shows a blank output for received data even when the connection is established properly. I've checked this question and so I've reprogrammed my server to first receive 2 bytes and then receive the string but it's not working. Can anyone explain? I've put some comments to explain the output.
Server.py
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
print "Socket Created..."
s.bind((str(socket.INADDR_ANY), 2609))
print "Socket bound to INADDR_ANY with port 2609..."
s.listen(5)
print "Socket listening for connections..."
print "Waiting for client to connect..."
(c, remote_addr) = s.accept()
print "Connection From" + str(remote_addr) + " accepted"
rec = 'pppppppppppppppppp'
print 'rec = ' + rec #Properly prints the initialized string
print 'lenght is ' + str(len(rec)) #prints length = 18
print "Receiving Data..."
leng = c.recv(2)
print "Data received..."
print leng #Does not print Anything
rec = c.recv(1024)
print rec #Does not print Anything
print 'lenght is ' + str(len(str(rec))) #Length is 0
c.close()
print "Client socket closed..."
s.close()
print "Server Socket closed..."
Output
% python Server.py
Socket Created...
Socket bound to INADDR_ANY with port 2609...
Socket listening for connections...
Waiting for client to connect...
Connection From('192.168.43.7', 39100) accepted
rec = pppppppppppppppppp
lenght is 18
Receiving Data...
Data received...
lenght is 0
Client socket closed...
Server Socket closed...
Upvotes: 1
Views: 801
Reputation: 22089
As the rest of your code on the sende side is unknown, I cannot identify the problem for sure, but there may be two possible reasons I can imagine:
You use the code as stated in your link. If you do not receive anything, this may indicate that the OutputStream
is bufferedand nothing is send, yet, although you called write(...)
. Try to flush()
it and see if you receive something.
In Python 3 recv
returns a bytes object as stated in the documentation:
The return value is a bytes object representing the data received.
In Python 2, you get a string, as stated in the documentation:
The return value is a string representing the data received.
Now, as you send your strings from a Java client, which encodes in UTF-8
, you should decode the bytes or string again at the receiver side with data.decode('utf-8')
to get a Unicode string.
Upvotes: 1