1

我正在尝试通过 Java 网络发送带有新行的文本。例如:

“你好\n这是一个新行”

这是我用于客户端的代码:

Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;

/*connect to server here*/

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;

while ((fromServer = in.readLine()) != null) {
    System.out.print("Server: " + fromServer);
    if (fromServer.equals("Bye.")) {
        break;
    }

    fromUser = stdIn.readLine();
    if (fromUser != null) {
        System.out.print("Client: " + fromUser);
        out.println(fromUser);
    }
}

out.close();
in.close();
stdIn.close();
kkSocket.close();

这是我用于服务器的代码:

/*Connect to server here*/
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
Protocol kkp = new Protocol();

outputLine = kkp.processInput(null);
out.println(outputLine);

while ((inputLine = in.readLine()) != null) {
    outputLine = kkp.processInput(inputLine);
    out.println(outputLine);
    if (outputLine.equals("Bye.")) break;
}

但它只返回第一行。

有没有人能指出我正确的方向,以便我可以使用新的线路?

4

1 回答 1

2

首先要注意的是该readLine()方法使用行终止符\n作为其中之一,剩余文本不包括在内的原因,为了发生这种情况,您必须readLine()再次调用该方法。在你的情况下,我会使用如下read(char[] cbuf, int off, int len)方法:char[]

而不是使用readLine()useread(char[] cbuf, int off, int len)来阅读如下

char[] cbuf = new char[1024];
while (in.read(cbuf, 0, cbuf.length) != null) {
    fromServer =  new String(cbuf);
    System.out.print("Server: " + fromServer);
    if (fromServer.equals("Bye.")) {
        break;
    }

    fromUser = stdIn.readLine();
    if (fromUser != null) {
        System.out.print("Client: " + fromUser);
        out.println(fromUser);
    }
}
于 2013-03-21T08:19:17.353 回答