I am writing a simple TCP server program. Everything is working properly, but the function recv() isn't.
import socket
import threading
def connectionHandler(sock):
data="#1111#Welcome on Server!"
sock.sendall(data.encode('ascii'))
username = sock.recv(1024)
password = sock.recv(1024)
print('{}, {}'.format(username, password))
conn.close()
HOST = socket.gethostname()
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(10)
while True:
conn, addr = s.accept()
print('Connected by', addr)
t = threading.Thread(target=connectionHandler, args=(conn,))
t.start()
conn.close()
When I comment all calls to recv(), the program is working properly, but when I want to receive answers from my client (android client on a smartphone), the program is blocking itself (I think that recv() is waiting for the message). I know that I have to set timeout, but it doesn't solve my problem. I want to send the message first and then receive something. Why does recv() block sendall()?
Android listener function:
public String listener(Socket x) throws IOException{
try {
Log.d("Listener","Started");
String inp;
BufferedReader in = new BufferedReader(new InputStreamReader(x.getInputStream()));
inp = in.readLine();
Log.d("Listener","Ended");
return inp;
} catch (UnknownHostException e1) {
e1.printStackTrace();
return "ERROR";
} catch (IOException e1) {
e1.printStackTrace();
return "ERROR";
}
}`
recvmay get half asend, or threesends combined into one buffer.recvgets both. Your secondrecvwaits forever for more data, but the client isn't sending any more because you already got everything.printtheusername; if it's the username and password crammed together, that's the whole problem. (And again, even if that isn't the whole problem, it's still a problem that you have to fix.)recvis giving youbytes, notstr; you have todecodeit to do anything useful. Even justprintis going to give youb'Franky'instead of theFrankyyou'd want.