【发布时间】:2021-12-10 21:38:21
【问题描述】:
我有一个类接收用户发送的消息并将它们打印在终端上,但现在我正在尝试编写一个从用户那里读取数据的类,将来自用户的字符串数据转换为字节数组,并将字节数组写入套接字。
我正在尝试使用 BufferedReader 从用户读取数据并使用 OutputStream 将字节数组写入套接字,但由于某种原因,我正在写入套接字的消息没有传递到服务器。
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String newLine = r.readLine();
while (r.ready() && newLine != null) {
// TODO: read data from the user, blocking until ready. Convert the
//string data from the user into an array of bytes and write
//the array of bytes to "socket".
byte[] message = newLine.getBytes();
OutputStream outputStream = s.getOutputStream();
outputStream.write(message);
}
s 是与我发送它的服务器和端口号相同的套接字!
我运行它时没有错误,所以我真的不知道为什么它不会将消息发送到套接字。
【问题讨论】:
-
你调试过你的代码吗?
outputStream.write(message)会被调用吗?您是否刷新流或至少关闭它?附带说明:不要使用getBytes(),因为这取决于系统的区域设置。而是使用getBytes(Charset)并在客户端和服务器代码中传递相同的字符集。