About Java Socket Communications

Asked 2 years ago, Updated 2 years ago, 72 views

I have a question about Java Socket communication.
If you have the following sources:
For this source res.write(request); after submitting the request,
Flushing with res.flush();.
The process of receiving the response follows.
What happens if I send a request and there is no response?
Will the processing stop?
Or will Exception occur?

OutputStreamWriter writer=newOutputStreamWriter(socket.getOutputStream());
res = new PrintWriter(writer);
requ = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Submit Request
res.write(request);
res.flush();

// response reception
SocketResponse response=req.parseResponse(requ);

java socket

2022-09-30 18:07

2 Answers

Set the timeout period for socket using the setSoTimeout method so that the program does not stop when there is no response.

 socket.setSoTimeout (2000);

It's kind of thing.(The timeout period is specified in milliseconds, so in the above example, SocketTimeoutException will occur if it is not received within 2 seconds.)

The Socket timeout default is 0 (infinite), so setting the timeout time can reduce the "program seems to have stopped…" problem.


2022-09-30 18:07

Does SocketTimeoutException Occur?
https://docs.oracle.com/javase/jp/8/docs/api/java/net/SocketTimeoutException.html


2022-09-30 18:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.