Hololens2在使用Socket通信时,无法同步消息

问题

Hololens使用Socket通信时,眼镜端无法同步消息,而使用UNet通信时可以正常使用

解决:

发现HoloLens不能进行同步通信,需要将同步通信改为异步通信:

//同步通信
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipAddress, port);  // 同步连接
byte[] buffer = new byte[1024];
int bytesRead = socket.Receive(buffer);  // 同步接收
socket.Send(data);  // 同步发送

改为:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.BeginConnect(ipAddress, port, ConnectCallback, socket);  // 异步连接
private void ConnectCallback(IAsyncResult result)
{
    
    
    Socket socket = (Socket)result.AsyncState;
    socket.EndConnect(result);
}
byte[] buffer = new byte[1024];
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, socket);  // 异步接收
private void ReceiveCallback(IAsyncResult result)
{
    
    
    Socket socket = (Socket)result.AsyncState;
    int bytesRead = socket.EndReceive(result);
}
socket.BeginSend(data, 0, data.Length, SocketFlags.None, SendCallback, socket);  // 异步发送
private void SendCallback(IAsyncResult result)
{
    
    
    Socket socket = (Socket)result.AsyncState;
    int bytesSent = socket.EndSend(result);
}

猜你喜欢

转载自blog.csdn.net/KIDS333/article/details/131293772
今日推荐