我使用Unity工具,在使用Socket类的时候,发现一个问题
下面是发送消息的方法
void StartClientReceive(string str){
//存在Client
//向客户端发送命令
if(clientSocketList.Count != 0){
for(int i = 0;i<clientSocketList.Count;i++){
clientSocketList[i].Send(Encoding.UTF8.GetBytes(str));
Debug.Log("向客户端" + clientSocketList[i].RemoteEndPoint + "发送了" + str + "的命令");
}
}else{
Debug.Log("没有客户端连接");
}
}
下面是接收消息的方法
void ReceiveMsg()
{
while(true){
if (clientSocket.Connected == false)
{
Debug.Log("与服务器断开了连接");
}
int lenght = 0;
byte[] data = new byte[1024];
lenght = clientSocket.Receive(data);
Debug.LogWarning("data is " + data);
Debug.LogWarning(lenght);
string str = Encoding.UTF8.GetString(data);
if (str.Contains("play"))
{
VideoCommond.instance.PlayRunable();
}else if (str.Contains("pause"))
{
VideoCommond.instance.PauseRunable();
}else if (str.Contains("stop"))
{
VideoCommond.instance.StopRunable();
}else if(str == "change"){
//问题出在这个Log一直打印不出来
Debug.LogWarning("Change");
}
Debug.LogWarning("收到命令" + str + str.Length);
}
}
可以看到在接收的地方我用 str == string 做判断就是不会执行,但是最后的收到命令那里输出的String确实是和判断的时候是一样的,那为什么直接用等于做判断会失效呢?是编码问题?还是data数据问题?怎么产生的这种问题?希望有人给我解答一下!谢谢!很困挠我。
假如你发送的String为
"asd"
则经过Encoding.UTF8.GetBytes转化为byte[]:
{97, 115, 100}
在接收端接收发送过来的数据时,你先创建了一个数组
byte[] data = new byte[1024];
然后经过clientSocket.Receive(data)方法,数组的内容会变成
{97, 115, 100, 0, 0, 0.....}
你直接用Encoding.UTF8.GetString(data)转化字符串,得到的是:
"asd/0/0/0/0....."
一般正确的做法是使用
Encoding.UTF8.GetString(recByte, 0, bytes);
recByte 为接受数据的数据;
0 为偏移值;
bytes 为clientSocket.Receive(data) 返回的数据长度。
解决了,但是问题出在哪里还是不明不白
发送端改为
void StartClientReceive(string str){
//存在Client
//向客户端发送命令
//以前是新建一个1024长度的数组在赋值,现在直接赋值
byte[] msgdata = Encoding.UTF8.GetBytes(str);
if(clientSocketList.Count != 0){
for(int i = 0;i<clientSocketList.Count;i++){
clientSocketList[i].Send(msgdata);
Debug.Log("向客户端" + clientSocketList[i].RemoteEndPoint + "发送了" + str + "的命令");
}
}else{
Debug.Log("没有客户端连接");
}
}