繁体   English   中英

服务器接受套接字但在此之后套接字无法接收任何内容

[英]Server accept socket but after that the socket cannot receive anything

在构建客户端 - 服务器聊天程序时,我遇到了一个非常奇怪的问题(因为这总是起作用)。

serversocket接受客户端的传入连接没有任何问题,但是当我尝试从套接字的输入流中读取时,整个方法阻塞并且仅在我关闭客户端套接字时释放。

我甚至尝试使用docs.oracle.com上的示例代码,但问题仍然存在。

任何人都可以指出我显然没有看到的错误吗?

服务器代码:

public class Server {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    System.out.println("Creating server socket");

    ServerSocket internetSocket = new ServerSocket(60000);
    if(!internetSocket.isClosed()) {

        while(true) {
            Socket s = internetSocket.accept();
            System.out.println("accepted socket!");

            BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));

            String line = null;
            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}
}

客户代码:

public class Client {

public static void main(String[] args) throws IOException {
    Socket s = null;
    try {
        s = new Socket("localhost", 60000);
    } catch (UnknownHostException ex) {
        Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
    }

    PrintWriter outStream = new PrintWriter(s.getOutputStream());
    for(int i=0; i<10; i++) {
        outStream.println("test");
        System.out.println("Sending the message \"test\"");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    s.close();
}
}

在创建printwriter printwriter时,您忘记添加true作为第二个参数

new PrintWriter(s.getOutputStream(), true);

它会自动冲洗。

方法readLine()正在等待\\ n字符出现在流中(方法阻塞,直到它看到结束行分隔符)。

尝试从客户端发送"test\\\\n" ,看看会发生什么。

并记住在客户端flush()输出流

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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