Socket接收正确的字节,字节转换为空字符串

时间:2013-08-22 12:24:12

标签: c# sockets unity3d

我一直在打破我一直在建造的这个系统中的一个错误。基本上,我使用套接字在两个C#应用程序之间进行通信。或者更确切地说是Unity C#脚本服务器和C#客户端应用程序。

通过手动测试,系统运行良好,无任何异常。 为了测试性能和多用户功能,我编写了一个测试人员类,它启动了多个线程(客户端),并在服务器上激活了大量的消息。这就是我的问题发生的地方......有时候。

当Socket发送或接收时,它返回一个整数容器,发送/接收的字节数。出现问题时,我可以看到正确的字节数到达服务器。但是,在将字节放入字符串后,突然我留下了一个空字符串,而不是我通常在这里看到的消息。

我对导致这个问题的原因感到茫然。我正在使用Encoding.Default.GetString()将字节转换为字符串。

任何帮助表示赞赏! 大卫

public void ReceiveFromClient (Socket handlerSocket)
{
    serverBuffer = new byte[iBufferSize]; //iBufferSize = 8192;

    int i = handlerSocket.Receive (serverBuffer);
    Debug.Log ("Bytes received: " + i);

    string message = Encoding.UTF8.GetString (serverBuffer, 0, i);
    Debug.Log ("Message received: " + message);

    //Do stuff with the message

}

bool SendMessageToUnity(string input)
    {//returns a bool saying whether the message was sent or not
        if (clientSocket != null)
        {  
            if (clientSocket.Connected)
            {
                byte[] bytes = Encoding.UTF8.GetBytes(input+"|");
                txtOutput.BeginInvoke(new Action(() => txtOutput.AppendText("Sending message: " + Encoding.UTF8.GetString(bytes) + Environment.NewLine)));

                int i = clientSocket.Send(bytes);
                txtOutput.BeginInvoke(new Action(() => txtOutput.AppendText("Sending "+i+" bytes. "+ Environment.NewLine)));
                return true;
            }                
        }
        return false;
    }

2 个答案:

答案 0 :(得分:0)

在将字节数组转换为字符串之前,请查找字节数组中的零值('\ 0')。

private string GetString(byte[] data)
{
  data = data.Where(b => b != 0).ToArray();
  return Encoding.UTF8.GetString(data);
}

答案 1 :(得分:0)

如果正确获得字节数组而不是编码中的问题。 检查发送编码通常是UTF8,但你必须检查它。

然后var inputStr = Encoding.UTF8.GetString(InputByteArray);

^^