gpt4 book ai didi

java - 对 readline socket java 感到震惊

转载 作者:行者123 更新时间:2023-12-01 18:33:51 25 4
gpt4 key购买 nike

我需要进行“静态”聊天,当我的客户端说“PAPO”时,我的服务器需要打印 PAPO 并将 PEPO 发送到客户端打印。但我在服务器上的 readLine() 处遇到问题,只需在此行停止即可。

import java.net.*;
import java.io.*;

public class Servidor {

public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(6543);
do {
Socket s = server.accept();
System.out.println("Servidor escutando...");
BufferedReader entrada = new BufferedReader(
new InputStreamReader(s.getInputStream()));
PrintWriter saida = new PrintWriter(s.getOutputStream());

System.out.println(entrada.readLine());

saida.write("PEPO");
System.out.flush();

entrada.close();
saida.close();
s.close();

} while (true);
} catch (UnknownHostException ex) {
System.out.println("Host desconhecido");
} catch (IOException ex) {
System.out.println("Erro na conexao: " + ex.getMessage());
}
}
}

客户:

import java.net.*;
import java.io.*;

public class Cliente {

public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6543);
do {
BufferedReader entrada = new BufferedReader(
new InputStreamReader(s.getInputStream()));
PrintWriter saida = new PrintWriter(s.getOutputStream());

saida.write("PAPO");

System.out.println(entrada.readLine());


entrada.close();
saida.close();
s.close();
} while (true);
} catch (UnknownHostException ex) {
System.out.println("Host desconhecido");
} catch (IOException ex) {
System.out.println("Erro na conexao: " + ex.getMessage());
}
}

}

最佳答案

看看您从客户那里写的内容:

saida.write("PAPO");

没有换行符,因此服务器不知道同一行中是否有更多文本。另外,因为您还没有刷新写入器,所以可能实际上没有发送任何数据。如果你只是将其更改为:

saida.write("PAPO\n");
saida.flush();

我怀疑你会发现它有效。

但是,我强烈建议您在使用 InputStreamReaderOutputStreamWriter 时指定编码,而不仅仅是使用平台默认值。如果您控制两端,UTF-8 通常是一个不错的选择。

关于java - 对 readline socket java 感到震惊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921402/

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