我的服务器正在发送以下数据:
{
"command": 23
}
我的客户正在接收以下数据:
"{\0\r\0\n\0 \0 \0\"\0c\0o\0m\0m\0a\0n\0d\0\"\0:\0 \02\03\0\r\0\n\0}\0"
正如你所看到的,我正在接收发送的数据,但与那些\0
混合在一起的数据。What is causing this?
也许与编码有关?
来自发送数据的服务器的方法:
public void GetBasicInfo()
{
JObject o = new JObject();
o.Add(COMMAND, (int)Command.GetBasicInfo);
byte[] package = GetBytes(o.ToString());
System.Diagnostics.Debug.WriteLine(o.ToString());
networkStream.Write(package, 0, package.Length);
networkStream.Flush();
}
private static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
客户端读取数据的方法:
private void CommsHandler(TcpClient tcpClient)
{
NetworkStream networkStream = tcpClient.GetStream();
while (true)
{
try
{
string message = ReadResponse(networkStream);
System.Diagnostics.Debug.WriteLine(message);
ParseMessage(message);
}
catch (Exception)
{
break;
}
}
Logger.Log(LogType.Warning, "Communication with server closed");
tcpClient.Close();
SearchForServer();
}
private static string ReadResponse(NetworkStream networkStream)
{
// Check to see if this NetworkStream is readable.
if (networkStream.CanRead)
{
var myReadBuffer = new byte[256]; // Buffer to store the response bytes.
var completeMessage = new StringBuilder();
// Incoming message may be larger than the buffer size.
do
{
var numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
} while (networkStream.DataAvailable);
return completeMessage.ToString();
}
return null;
}