问题
我在我的套接字客户端中读取了第一个字节以检查连接:
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();