0

我正在尝试在 java 中开发客户端/服务器通信应用程序。但在最初阶段,我无法使用BufferedReader.readline(). 我用谷歌搜索了很多,但找不到我的问题的具体答案。
调试客户端应用程序显示客户端应用程序在response.readline().

服务器:

package myserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MyServer {
    public static void main(String[] args) {
        String[] tokens = new String[10];
        int count = 0;
        ServerSocket server = null;
        try {
            server = new ServerSocket(16);
        } catch (IOException ex) {
            Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (server != null) {
            while (true) {
                PrintWriter response;
                BufferedReader command;
                String inCommand;
                try {
                    Socket client = server.accept();
                    System.out.println("Connected!");
                    response = new PrintWriter(client.getOutputStream());
                    command = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    response.print("EHLO\r\n");
                    command.read(); //just to stop the application to start a new iteration
                } catch (IOException ex) {
                    Logger.getLogger(OdeskServer.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

客户:

package myclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MyClient {

    public static void main(String[] args) {
        Socket server = null;
        PrintWriter command;
        BufferedReader response;
        BufferedReader Console = new BufferedReader(new InputStreamReader(System.in));
        try {
            server = new Socket("175.107.231.218", 16);
            System.out.println("Connected");
            command = new PrintWriter(server.getOutputStream());
            response = new BufferedReader(new InputStreamReader(server.getInputStream()));
            while (server.isBound()) {
                String input = response.readLine(); //Here is where the communication halts
                System.out.print(input);
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(OdeskClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

对这个问题有任何想法吗?

4

1 回答 1

3

您可能需要response.flush()从服务器调用以确保套接字不会缓冲您的消息以等待更多写入一起批处理。

于 2013-03-15T15:48:21.353 回答