HoloLens眼镜端的Socket客户端发送和接受消息

本文分享了HoloLens眼镜端的Socket通信代码实现,针对UWP系统的兼容性问题,提供了详细的Socket连接与数据收发解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近好久没有写博客了,因为最近出差比较多,下面就是HoloLens眼睛端Socket通信的代码,眼镜端比较特殊,系统用的是UWP的系统,好多一些Socket语法在眼镜端都没办法兼容,我在网上找了比较久才找到教程。
废话不多说,下面就是代码

using System;
using UnityEngine;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
#if !NETFX_CORE 
using System.Net;
using System.Net.Sockets;
#else
using Windows.Networking.Sockets;
using Windows.Networking.Connectivity;
using Windows.Networking;
#endif


public class SocketClient
{
    private int m_Port;   
    private string m_Ip;   

    private Socket m_Socket;                         
    private SocketAsyncEventArgs m_ReceiveSaea;       
    private SocketAsyncEventArgs m_RendSaea;
    private SocketAsyncEventArgs m_ConnetedSaea;

    private const int m_ReceiveMaxLength = 1024;
    byte[] recv_buf = new byte[m_ReceiveMaxLength];

    public void Init(string ip, int port)
    {
        this.m_Port = port;
        this.m_Ip = ip;
        Connect();
    }

    public void Connect()
    {
         try
         {
             m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             m_ConnetedSaea = new SocketAsyncEventArgs();
             m_ConnetedSaea.Completed += new EventHandler<SocketAsyncEventArgs>(ConnetedCall);//设置回调方法                                                                        
             m_ConnetedSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(m_Ip), m_Port);    //设置远端连接点,一般用于接消息
             m_RendSaea = new SocketAsyncEventArgs();
             //连接到服务器
             m_Socket.ConnectAsync(m_ConnetedSaea);
         }
         catch (Exception e)
         {
             Debug.Log(e);
         }
    }

    private void ConnetedCall(object sender, SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            m_ReceiveSaea = new SocketAsyncEventArgs();
            m_ReceiveSaea.SetBuffer(recv_buf, 0, recv_buf.Length);
            m_ReceiveSaea.Completed += new EventHandler<SocketAsyncEventArgs>(ReceiveCall);
            m_Socket.ReceiveAsync(m_ReceiveSaea);
        }
        else 
        {
            Debug.Log(e.SocketError);
        }
    }
    #region 接收数据
    private int m_FragmentLen;
    private byte[] m_Fragment;
    /// <summary>
    /// 回调读取网络数据、检查是否断线。
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ReceiveCall(object sender, SocketAsyncEventArgs e)
    {
        ProcessReceive(e);
    }

private void ProcessReceive(SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            // 检查远程主机是否关闭连接
            if (e.BytesTransferred > 0)
            {
                //TODO 处理数据
                byte[] data = new byte[e.BytesTransferred];
                Array.Copy(e.Buffer, e.Offset, data, 0, data.Length);//从e.Buffer块中复制数据出来,保证它重用
               //解析消息
             
                if (!m_Socket.ReceiveAsync(e))//为接收下一段数据,投递接收请求,这个函数有可能同步完成,这时返回false,并且不会引发SocketAsyncEventArgs.Completed事件
                {
                    //同步接收时处理接收完成事件
                    ProcessReceive(e);
                }
            }
        }
    }

    #endregion
    #region 发送消息
    /// <summary>
    /// 将消息入队发送
    /// </summary>
    /// <param name="data"></param>
    private void Send(byte[] data)
    {
        m_MsgbyteQueue.Enqueue(data);
    }

    private Queue m_MsgbyteQueue = new Queue();

    /// <summary>
    /// 在Update中调用此方法,消息会一条一条发送
    /// </summary>
    public void SendMsg()
    {
        if(m_MsgbyteQueue.Count>0&&!m_Sending)
        {
            m_Sending = true;
            byte[] data= (byte[])m_MsgbyteQueue.Dequeue();
            Debug.Log("Start sending, the number of bytes sent this time is" + data.Length);
            m_RendSaea.SetBuffer(data, 0, data.Length);
            m_RendSaea.Completed += SendCallBack;
            m_Socket.SendAsync(m_RendSaea);
        }
    }
    private bool m_Sending;
    private void SendCallBack(object sender, SocketAsyncEventArgs e)
    {
        Debug.Log("Send Succeed");
        m_RendSaea.Completed -= SendCallBack;
        m_Sending = false;
    }
#endregion
    public void Dispose()
    {
        //base.Dispose();
        //最后关闭服务器  
        if (m_Socket != null && m_Socket.Connected)
        {
            m_Socket.Shutdown(SocketShutdown.Receive);
            m_Socket.Shutdown(SocketShutdown.Send);
            m_ReceiveSaea.Dispose();
        }
        if (m_RendSaea != null) m_ConnetedSaea = null;
        if (m_RendSaea != null) m_RendSaea.Dispose();
        m_RendSaea = null;
    }
}
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值