readLine()中'Socket closed';

时间:2016-11-25 22:43:42

标签: java tcp bufferedreader

每当我尝试从服务器接收消息时,我都会收到以下异常。这发生在客户端的rcvdId = inFromServer.readLine();行。服务器确实收到我发送的变量。变量serialToNucleo.nucleoAnswer甚至包含一个字符串。我知道代码还没有完全正常工作,因为我只发送一个变量,但我正在努力。

客户端:

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();

}

服务器:

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

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)

1 个答案:

答案 0 :(得分:0)

'套接字关闭'意味着关闭了套接字,然后继续使用它。

与连接丢失'无关。

它发生在这里:

out.close();

关闭套接字的输入或输出流会关闭套接字。更改为out.flush()

注意您的服务器代码像筛子一样泄漏插座。