/// <summary> /// 处理数据接收回执 /// </summary> private void ProcessRsp() { Task.Factory.StartNew(() => { RspBuffer buffer = null; while (!rspQueue.IsEmpty) { if (rspQueue.TryDequeue(out buffer)) { var rsp = UDPPack.PackRsp(buffer.Package); try { socket.SendTo(rsp, buffer.Point); } catch (SocketException ex) { Debug.WriteLine(ex); break; } catch (ObjectDisposedException ex) { Debug.WriteLine(ex); this.sendQueue.Clear(); this.recsession.Close(); break; } } } isPspStop = true; }); }
public void AddData(byte[] data, int len) { var p = UDPPack.UnPack(data, len); if (sessions == null) { sessions = new SubPackage[p.PackNum]; } sessions[p.SeqId] = p; }
/// <summary> /// 发送数据 /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <param name="data"></param> /// <returns></returns> public void Send(string host, int port, byte[] data) { var p = UDPPack.Pack(data); p.RemoteHost = new IPEndPoint(IPAddress.Parse(host), port); sendQueue[p.SessionId] = p; foreach (var k in p.Packages) { SendTo(k, p.RemoteHost); } if (isRecStop) { isRecStop = false; StartRecvice(); } if (isSendStop) { isSendStop = false; ReSend(); } }
/// <summary> /// 处理接收的数据 /// </summary> private void ProcessRecvice() { Task.Factory.StartNew(() => { RecviceBuffer buffer = null; UDPPackage package; while (!recQueue.IsEmpty) { if (recQueue.TryDequeue(out buffer)) { var p = UDPPack.UnPack(buffer.Data, buffer.Len); if (p.PackNum == 0) { continue; } if (p.DataType == 1) { if (sendQueue.TryGetValue(p.SessionId, out package)) { package.Remove(p.SeqId); } } else { rspQueue.Enqueue(new RspBuffer() { Point = buffer.Point, Package = p }); //准备回执 if (recsession.AddData(buffer.Point.ToString(), p)) { var buf = recsession.GetData(buffer.Point.ToString(), p.SessionId); if (UDPPackProcess.Instance.dicFilter.ContainsKey(buffer.Point.ToString() + "," + p.SessionId)) { continue; } else { UDPPackProcess.Instance.dicFilter[buffer.Point.ToString() + "," + p.SessionId] = DateTime.Now.Second; } if (UDPCall != null) { UDPCall(this, buf, new SocketRsp() { Address = buffer.Point.Address.ToString(), Port = buffer.Point.Port }); } else { //只能复制 var tmp = new RecviceBuffer { Data = new byte[buffer.Data.Length], Len = buffer.Len }; Array.Copy(buffer.Data, 0, tmp.Data, 0, tmp.Data.Length); block.Add(tmp); } } if (isPspStop) { isPspStop = false; ProcessRsp(); } } buffer.Return(); } } isProcessRecStop = true; }); }