我一直在打破我的头在这个系统中,我一直在建设一个错误。基本上,我使用套接字在两个C#应用程序之间进行通信。或者说是一个Unity C#脚本服务器和一个C#客户端应用程序。套接字接收正确的字节,字节翻译为空字符串
通过手动测试,系统工作得很好,没有任何异常。 为了测试性能和多用户功能,我编写了一个启动多线程(客户端)的测试程序类,并在服务器上启动了X个消息。这是我的问题发生的地方......有时。
当一个套接字发送或接收时,它返回一个整数容器发送/接收的字节数量。发生问题时,我可以看到正确的字节数到达服务器。但是,将字节放入一个字符串之后,突然间我留下了一个空字符串,而不是我通常在此处看到的消息。
我不知道是什么原因导致此问题。我使用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;
}
您应该使用'Encoding.UTF8',而不是'Encoding.Default'。 'Encoding.Default'可以在不同的计算机之间有所不同。 – xanatos
发布您的代码.. – I4V