0

错误说套接字已关闭...我可以很好地发送到服务器,我可以很好地从服务器接收,但是一旦我尝试发送和接收,我总是会收到“套接字已关闭”错误。

服务器:

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString;
        while ((decodedString = in.readLine()) != null) {
            System.out.println(decodedString);
        }
        in.close();

        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());           
        osw.write("return: "+decodedString);
        osw.flush();         
        osw.close();

客户:

    Socket c = new Socket("localhost",4040);    
    OutputStreamWriter osw = new OutputStreamWriter(c.getOutputStream());
    osw.write("Test");
    osw.flush();
    osw.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
    String decodedString;
    while ((decodedString = in.readLine()) != null) {
        System.out.println(decodedString);
    } 
    in.close();
    c.close();
4

1 回答 1

3

这是因为当您关闭流的 ( osw.close();) 之一时,socked 也会关闭。来自Socket.getOutputStream的 javadoc:

关闭返回的 {@link java.io.OutputStream OutputStream} 将关闭关联的套接字。

尝试刷新流,但仅在完成后关闭它们。

于 2013-08-10T15:09:09.357 回答