ThaSam ThaSam - 10 days ago 7
Java Question

'Socket closed' in readLine();

Whenever I try to receive a message from my Server, I get the exception below. This happens at the line

rcvdId = inFromServer.readLine();
in the Client. The server does receive the variables I am sending. The variable
serialToNucleo.nucleoAnswer
even contains a string. I know the code will not fully work yet, as I am only sending one variable, but I am working on that.

Client:

try {

Socket skt = new Socket("192.168.1.9" , 6789);

BufferedReader inFromServer = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + vraagTemp + " and " + vraagId+"'\n");
out.print(vraagTemp + "\n");
out.print(vraagId + "\n");
out.close();
rcvdId = inFromServer.readLine();
rcvdTemp = inFromServer.readLine();

WriteToDb writeToDb = new WriteToDb();
writeToDb.SendDataToDb(rcvdId,rcvdTemp);

skt.close();

}


Server:

while (true) {

Socket skt = serverSocket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
ontvServer = inFromClient.readLine();
id = inFromClient.readLine();
System.out.println("Received: " + ontvServer);

if (id != null && ontvServer != null)
{
serialToNucleo.SetupComm(ontvServer, id);
}
else
{
Thread.sleep(100);
}

if (serialToNucleo.nucleoAnswer!= null) {
out.print(serialToNucleo.nucleoAnswer + "\n");
id = null;
ontvServer = null;
}
else
{
Thread.sleep(100);
}

}


Stacktrace from the exception thrown

java.net.SocketException: socket closed at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at ChatClient.main(ChatClient.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

EJP EJP
Answer

'Socket closed' means that you closed the socket and then continued to use it.

It has nothing to do with 'connection lost'.

It happens here:

out.close();

Closing either the input or output stream of a socket closes the socket. Change to out.flush().

NB Your server code leaks sockets like a sieve.

Comments