gpt4 book ai didi

java - Java 网络,客户端多行响应中出现 'readLine()'

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:10 25 4
gpt4 key购买 nike

我目前正在编写一个邮件客户端,它只需打开与邮件服务器的连接并接收来自它的响应。

但是,当我收到服务器的响应时,它仅在响应是一行时才有效。当响应多于一行(多行)时,则仅接收第一行响应。

如果我可以知道响应的格式,例如每行末尾有\n,那么格式化响应会更容易。但由于我只写客户端而不是服务器,所以我也不知道响应格式。

下面是我编写的代码。

public class Main {
private static Socket client;
private static final BufferedReader br
= new BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) {
try {
/* Input format checking before opening a connection,
the input must be a form of mail_server and port_number */
if (args.length != 2)
System.exit(1);

/* Set up the connection to mail server from the command line */
client = new Socket(args[0], Integer.parseInt(args[1]));

/* Initialize sender that sends message to the server */
PrintStream sender = new PrintStream(client.getOutputStream());

/* Initialize receiver that receives message from the server */
BufferedReader receiver
= new BufferedReader(
new InputStreamReader(client.getInputStream()));

while (true) {
/* Flushing buffer */
String message;

/* Printing the resulting response from the server */
while ((message = receiver.readLine()) != null) {
System.out.println(message);
}

/* Get input message from the user */
message = br.readLine();

/* If the user inputs "exit", then the program terminates */
if (message.equals("exit")) System.exit(1);

/* If not exit, send the message to server */
sender.println(message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

}

我也尝试过,

// Assuming that the output format has '\n' at the end of each lines
String[] messages = receiver.readLine().split("\n");

但它也只打印出响应的第一行。

我在Java server-client readLine() method看到了非常类似的问题但问题已经通过编辑服务器代码解决了,我只能更改客户端代码。

有人可以给我建议吗?

提前致谢。

最佳答案

嗯,我让它与 netcat 一起工作,例如:

nc -l -p 31337

启动 netcat 后,您可以输入一些输入,这些输入将在连接后发送到客户端。

所以使用 netcat 就可以了。我建议仅将变量用于一个目的。

        while(true){
/* Flushing buffer */
String SvMessage;
while (!receiver.ready()){} //wait for buffer
/* Printing the resulting response from the server */
while (receiver.ready()){
SvMessage = receiver.readLine();
System.out.println(SvMessage);
}

/* Get input message from the user */
String userMessage = "hello";

/* If the user inputs "exit", then the program terminates */
if (userMessage.equals("exit")) System.exit(1);

/* If not exit, send the message to server */
sender.print(userMessage + "\r\n");
}

我做了一些改变:1.) 将 while 条件更改为 br.ready()2.) 使用 PrintStream.print(message + "\r\n) 代替 PrintStream.println3.) 不使用 BufferedReader 进行用户输入,只发送“命令”(或你好)4.) 添加 while (!receiver.ready()){} 来等待缓冲区填充

因此客户端现在将始终使用新命令(或“hello”)回复服务器。 =)

希望这有帮助

关于java - Java 网络,客户端多行响应中出现 'readLine()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40688479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com