iosamammohamed iosamammohamed - 6 months ago 63
Java Question

Socket doesn't send data until it is closed

i have a simple application which create a socket between java(server) and python(client).
The main function of the python code is to take data from user and send it to the server(java code)

here's the python code

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))

while True:
data = input("Enter data to send : ")
if(data == 'q'):
break

client_socket.sendall(data.encode('utf-8'))

client_socket.close()


and here's the java code

String fromclient;

ServerSocket Server = new ServerSocket (5000);


while(true)
{
Socket connected = Server.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
fromclient = inFromClient.readLine();

if ( fromclient.equals("q") ){
connected.close();
break;
}else {
System.out.println(fromclient);
}
}


when I write any text and click Enter, nothing goes to java code and nothing printed to the console, but when i send 'q' from python, the python code closed and all the data i wrote are now printed in java console.
I have no idea what is the reason of this, and how i can fix it.

Answer Source

The Java code waits for a line-break, but the Python part does not send one (input provides no line-break in the string it returns).

Try

client_socket.sendall((data+'\n').encode('utf-8'))


As @Kayaman suggests, the accept is in a wrong place (and also is the BufferedReader).

Socket connected = Server.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader (connected.getInputStream()));
while(true) 
{
    fromclient = inFromClient.readLine();

would be a better order.

Also, Python client does not send the 'q' in its current form. So the if with the fromclient.equals("q") will not close the socket, the code will just die on the next readLine() instead. Re-order the Python part too:

data = input("Enter data to send : ")
client_socket.sendall((data+'\n').encode('utf-8'))

if(data == 'q'):
    break
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download