简体   繁体   中英

Java socket writeByte and newline

I got a question for something I can't seem to understand.

If I use the snippet:

DataOutputStream dataoutput = new DataOutputStream(Socket.getOutputStream());

dataoutput.writeBytes(diagnostics);
dataoutput.flush();

The output:diagnostics that is sent from server to client hangs, where even using .flush() will not help. Only closing the socket will release the data packet.

However, if I add a newline character:

dataoutput.writeBytes(diagnostics+"\n");

it works perfectly. And if you duplicate the code,

dataoutput.writeBytes(diagnostics);
dataoutput.writeBytes(diagnostics);

You get the same output as the one with the /newline without duplicate data. Why?

EDIT: Client-side.

incoming = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
response = incoming.readLine();

Like the good lads puts in the comment you should use a flush to force send the payload to destination of the stream. But if that isn't working i suggest to try the following :

    DataOutputStream dataoutput = new DataOutputStream(System.out);

    dataoutput.writeBytes(diagnostics);
    dataoutput.flush();

So now the destination will be the "local" console. and no remote connection is between the source and the destination of the stream, perhaps you can try for yourself if anything is working properly "locally" (and focus in the DataOutputStream behaviour) and then start to tackle the remote streaming process.

Is it not to much, but hope it helps a little!

Greetings!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM