2

问题

我在我的套接字客户端中读取了第一个字节以检查连接:

ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.BIG_ENDIAN);
...
int dataInt = clientSocket.getInputStream().read();

文档

从此流中读取单个字节并将其作为 0 到 255 范围内的整数返回。如果已到达流的末尾,则返回 -1。

之后我想将此字节与下一个输入字符串拼接。我将此整数字节转换为字符

b.putInt(dataInt);
byte[] dataByte = b.array();
final String data;

并检查它。如果 dataInt != -1,我必须将此裁剪后的字节返回到新字符串中:

if(dataInt != -1)
{
    String c = new String(dataByte);
    Log.v("MSG", c);
    data = c + inToServer.readLine();
}
else
{
    data = inToServer.readLine();
}

为什么我在日志中看到“MSG, ������MY MESSAGE”?如何正确获取字符串?


更新,我如何发送消息:

byte[] buf = str.getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
outToServer.writeBytes("\n");
outToServer.flush();
4

4 回答 4

2
if(dataInt != -1)
{
    String c = new String(dataByte, "UTF-8");
    Log.v("MSG", c);
    data = c + inToServer.readLine();
}
else
{
    data = inToServer.readLine();
}
于 2012-11-11T20:40:33.323 回答
1

好的,所以在您的服务器端只需使用收到的 byte[] 执行此操作即可。不需要字节缓冲区,也不需要以任何方式对其进行操作。

String str = new String(recievedBytes); 
于 2012-11-11T20:40:55.240 回答
0

我建议您为此使用IOUtils.toString。它促进了许多无聊且容易出错的输入/输出流操作。

这是解释如何设置项目以使用 apache IO commons的答案。

于 2012-11-11T20:48:59.067 回答
0

天哪,我做到了。解决方案:

byte[] b1 = new byte[1];
int dataInt = clientSocket.getInputStream().read();
b1[0] = (byte)dataInt;
于 2012-11-11T21:16:58.613 回答