public void Receive() { #if XRUWP && !UNITY_EDITOR async void receive() { DatagramSocket udp = new DatagramSocket(); await udp.BindServiceNameAsync(ip.Port.ToString()); udp.MessageReceived += async(s, r) => { using (DataReader dr = r.GetDataReader()) { byte[] d = new byte[dr.UnconsumedBufferLength]; dr.ReadBytes(d); if (Net.LogEnable) { Debug.Log("收到" + _ip + ",udp数据长度:" + d.Length); } buffer.Write(d); if (buffer.IsRead()) { NetData n = XRMaker.NetData.ReadBuffer(buffer.Read()); n.RemoteIP = _ip; Net.NetData.Add(n); } } }; } receive(); #else receive = new Thread(() => { EndPoint _ip = new IPEndPoint(IPAddress.Any, 0); byte[] d = new byte[4096]; while (true) { try { int l = udp.ReceiveFrom(d, ref _ip); if (LogEnable) { Debug.Log("收到" + _ip + ",udp数据长度:" + l); } if (l < d.Length) { byte[] _d = new byte[l]; Array.Copy(d, 0, _d, 0, l); buffer.Write(_d); } else { buffer.Write(d); } if (buffer.IsRead) { NetData n = NetData.ReadBuffer(buffer.Read()); n.RemoteIP = (IPEndPoint)_ip; Net.NetDatas.Add(n); } } catch (Exception e) { Debug.LogError("udpInfo:" + e.Message.ToString()); } } }); receive.Start(); #endif }
public void Receive() { Thread r = new Thread(() => { try { byte[] d = new byte[4096]; tcp.ReceiveTimeout = Net.Timeout; int l = tcp.Receive(d); while (l > 0) { if (LogEnable) { Debug.Log("收到" + ip + ",tcp数据长度:" + l); } if (l < d.Length) { byte[] _d = new byte[l]; Array.Copy(d, 0, _d, 0, l); buffer.Write(_d); } else { buffer.Write(d); } if (buffer.IsRead) { NetData n = NetData.ReadBuffer(buffer.Read()); n.RemoteIP = ip; Net.NetDatas.Add(n); } l = tcp.Receive(d); } } catch (Exception e) { Debug.LogError("tcpInfo:" + ip + ":" + e.Message.ToString()); } finally { if (LogEnable) { Debug.Log("tcp接收监听关闭"); } Close(); } }); r.Start(); //心跳包线程 Thread h = new Thread(() => { while (true) { Thread.Sleep(Timeout / 2); if (tcp != null) { NetData n = new NetData(NetMessageType.Heartbeat); n.Write(DateTime.Now.Millisecond); Send(n.ToBuffer()); } else { return; } } }); h.Start(); }