【发布时间】:2012-01-19 13:09:54
【问题描述】:
我整天都在和这个作斗争。我需要在 C# 服务器和 Java 客户端之间发送字符串 (JSON)。我必须将前 4 个字节(总是 4 个字节)作为消息的长度(标题,所以我们知道消息的其余部分有多长),然后是消息的正文。流在应用程序的生命周期内保持打开状态。就我个人而言,我会用“\n”分隔每条消息,然后使用 readLine(),但客户端需要这种方式。
我需要 C# 端以及 Java 端来发送和接收这些消息。不太清楚如何编码和解码所有内容。
我一直在玩的一些位:
C# 发送
byte[] body = Encoding.ASCII.GetBytes(message);
byte[] header = BitConverter.GetBytes((long) body.Length);
foreach (byte t in header)
{
networkStream.WriteByte(t);
}
foreach (byte t in body)
{
networkStream.WriteByte(t);
}
我还没有到 C# 接收。 Java 发送:
byte[] dataToSend = data.getBytes();
byte[] header = ByteBuffer.allocate(4).putInt(dataToSend.length).array();
ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(header);
output.write(dataToSend);
output.writeTo(outputStream);
Java 接收:
byte[] header = new byte[4];
int bytesRead;
do {
Debug.log("TCPClient- waiting for header...");
bytesRead = reader.read(header);
ByteBuffer bb = ByteBuffer.wrap(header);
int messageLength = bb.getInt();
Debug.log("TCPClient- header read. message length (" + messageLength + ")");
byte[] body = new byte[messageLength];
do {
bytesRead = reader.read(body);
}
while (reader.available() > 0 && bytesRead != -1);
}
while (reader.available() > 0 && bytesRead != -1);
我知道代码并不完整,但谁能提供任何帮助?
【问题讨论】:
-
我会在 C# 上使用 TextReader 和 StreamWriter。更容易,您可以直接使用字符串写入和读取消息。
-
正如我所说,我别无选择。我必须发送前 4 个字节作为消息的长度。
标签: c# java string sockets bytearray