【发布时间】:2015-02-10 23:03:09
【问题描述】:
我已经在服务器和 i 客户端之间建立了一个套接字连接。现在我正在尝试将数据从我的客户端发送到服务器。实际上,数据是一个字节数组,其中包含索引 14 到 27 中的数字。数组的示例如下:
{27, 14, 16, 18, 20, 22, 14, 17, 15, 17} and so on.
已将其制成字节数组,因为数据必须以字节为单位。
困难在于,当我从数组向服务器发送一行时,除了字符串之外,我不知道如何读取它。如果它是一个字符串,它会返回一些奇怪的数字,就像你在图片中看到的那样。
一些代码我是如何做到的:
发件人
for (int i = 0; i < data.length; i++) {
writer.write(data[i]);
}
writer.flush();
writer.close();
接收者
public void readResponse(Socket client) throws IOException{
String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println("Response from client:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
}
我的字节数组是这样制作的:
private byte data[] = new byte[12];
如果我将其更改为大写字节,我可以使用我的代码读取它,但我不确定它是否以字节为单位?必须使用一些数学来计算平均值。
私有字节数据[] = 新字节[12];
那么,我该如何阅读呢?
更新:
所以我知道我将使用不同的输入/输出流。现在我也把它改成了数据输入和输出流。
代码如下:
服务器
public void readResponse(Socket client) throws IOException{
DataInputStream input = null;
byte data;
try {
input = new DataInputStream(client.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
System.out.println("Response from client:");
while ((data = input.readByte()) != -1) {
System.out.println(data);
}
}
客户
public void sentData(Socket client) throws IOException{
DataOutputStream output = null;
try {
output = new DataOutputStream(client.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}
for (int i = 0; i < data.length; i++) {
output.write(data[i]);
}
output.flush();
output.close();
}
正如您在我的客户端中看到的,我想一次向服务器发送一个字节,但它仍然显示奇怪的数字,例如 [?][?][?]。
【问题讨论】:
标签: java sockets byte bytearray