与BufferedReader挂起的客户端 - 服务器通信

时间:2015-09-10 21:40:06

标签: java sockets client-server

我正在测试客户端 - 服务器通信。

我有一台服务器应该接收消息并打印它们,并使用System.in发送从Socket获取的消息。客户端从Socket读取消息,并发回一些消息。但由于某种原因,服务器和客户端在检查是否有来自另一端的消息(readLine())时会被锁定。

此客户:

public void run() {
    try {
        Log.i("DataManager", "Trying to connect to server");    
        socket.connect(new InetSocketAddress(ADDRESS, PORT), 3000);
        Log.i("DataManager", "Connected to: " + socket.getInetAddress());   

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush

        String inputLine;
        while (socket.isConnected()) {
            if ((inputLine = in.readLine()).isEmpty()){
                Log.i("DataManager", "Server says: " + inputLine);  
            }

            synchronized (outcoming){
                if (!outcoming.isEmpty()){
                    for (int i = 0; i < outcoming.size(); i++){
                        out.println(outcoming.get(i));
                        outcoming.remove(i);
                    }
                }
            }

        }
    } 
    ...
}//

服务器:

ServerSocket listener = new ServerSocket(PORT);
    try {
        Socket socket;
        socket = listener.accept(); //waits for connection
        System.out.println("Client connected: " + socket.getInetAddress());

        BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
        BufferedReader clientIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush

        String inputLine;
        out.println("Hello, you are connected to server" + listener.getInetAddress());
        while (true){
            if ((inputLine = clientIn.readLine()).isEmpty()){
                System.out.println("Client says: " + inputLine);
            }
            String line = sysRead.readLine();
            if (line.equals("stop")){
                break;
            } else {
                out.println(line);
            }
        }
        socket.close();
    } 

我尝试通过用readLine包含if(in.ready())语句来解决此问题,但它根本没有帮助。我一直在浏览谷歌,发现这是由readLine()寻找eof的事实引起的,而来自套接字的流只在套接字断开时结束。我不知道如何解决这个问题,除了编写某种协议,我用特定的序列结束我的消息。有没有更好的解决这个问题的方法?

0 个答案:

没有答案