public void Bind() { cacheManager.BufferSize = BufferSize; cacheManager.Capacity = TotalBufSize * MByte; tokenPool.MaxLeftNum = TokenMaxLeftNum; socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.SendBufferSize = 64 * 1024; socket.ReceiveBufferSize = 64 * 1024; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000); if (string.IsNullOrEmpty(Host)) { localEndPoint = new IPEndPoint(IPAddress.Any, Port); } else { localEndPoint = new IPEndPoint(IPAddress.Parse(Host), Port); } socket.Bind(localEndPoint); receivebuffer = new byte[BufferSize]; receiveSocketArgs = new SocketAsyncEventArgs(); receiveSocketArgs.RemoteEndPoint = localEndPoint; receiveSocketArgs.Completed += IO_Completed; receiveSocketArgs.SetBuffer(receivebuffer, 0, receivebuffer.Length); AsyncUdpUserToken token = new AsyncUdpUserToken(); token.Socket = socket; token.IPAddress = localEndPoint.Address; receiveState = new AsyncSocketUDPState(); receiveState.Data = receivebuffer; receiveState.Remote = localEndPoint; receiveState.IPAddress = localEndPoint.Address; receiveState.Socket = socket; }
private void Recieve(IAsyncResult ar) { AsyncSocketUDPState so = ar.AsyncState as AsyncSocketUDPState; int len = -1; try { len = socket.EndReceiveFrom(ar, ref so.Remote); // byte[] buf = null; bool r = false; int index = 0; if (IsFixCache) { if (cacheManager.SetBuffer(out buf, out index)) { r = true; } } else { if (cacheManager.GetBuffer(out buf)) { r = true; } } // if (!r) { buf = new byte[len]; } // Array.Copy(receiveState.Data, 0, buf, index, len); if (EnableHeart) { // AsyncUdpUserToken cur = null; IPEndPoint remote = so.Remote as IPEndPoint; string id = remote.ToString() + remote.Port; if (dicToken.TryGetValue(id, out cur)) { cur.DataTime = DateTime.Now; } else { cur = new AsyncUdpUserToken(); cur.IPAddress = localEndPoint.Address; cur.Socket = socket; cur.Remote = so.Remote; dicToken[id] = cur; } bool rCpm = true; if (len == HeartBytes.Length) { for (int i = 0; i < len; i++) { if (buf[i + index] != so.Data[i + so.OffSet]) { rCpm = false; break; } } } if (rCpm) { //是心跳包 Recvice(); return; } } //不要进行耗时操作 DoEventRecvice(buf, so.Remote, index, len, r); } catch (Exception) { //TODO 处理异常 } finally { Recvice(); } }