Exemplo n.º 1
0
 /// <summary>
 /// 发送数据
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="remote"></param>
 public void Send(IPEndPoint remote, byte[] bits)
 {
     try
     {
         if (ServerType == UDPServerType.ASCII)
         {
             LOG.InfoFormat("({3}) Send {0}:{1},body:{2}", remote.Address.ToString(), remote.Port,
                            Encoding.ASCII.GetString(bits).Replace("?", "."), Name);
         }
         else
         {
             LOG.InfoFormat("({3}) Send {0}:{1},body len:{2}", remote.Address.ToString(), remote.Port,
                            bits.Length, Name);
         }
         if (PrintHex)
         {
             PrintUtils.PrintHex(bits);
         }
         RaisePrepareSend(udpReceiveState);
         _server.BeginSend(bits, bits.Length, remote, new AsyncCallback(SendCallback), udpReceiveState);
     }
     catch (Exception)
     {
         RaiseOtherException(udpReceiveState);
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// 接收数据的方法
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveDataAsync(IAsyncResult ar)
        {
            AsyncUDPState udpState = ar.AsyncState as AsyncUDPState;
            IPEndPoint    remote   = null;

            byte[] buffer = null;
            try
            {
                if (ar.IsCompleted)
                {
                    buffer = _server.EndReceive(ar, ref remote);
                    if (ServerType == UDPServerType.ASCII)
                    {
                        string receiveString = Encoding.ASCII.GetString(buffer);
                        LOG.InfoFormat("({4}) Received {0}:{1},len:{2},body:{3}", remote.Address, remote.Port, buffer.Length, receiveString, Name);
                    }
                    else
                    {
                        LOG.InfoFormat("({3}) Received {0}:{1},len:{2}", remote.Address, remote.Port, buffer.Length, Name);
                    }
                    if (PrintHex)
                    {
                        PrintUtils.PrintHex(buffer);
                    }
                    udpState.remote = remote;
                    //触发数据收到事件
                    RaiseDataReceived(udpState, buffer);
                    //lock (this)
                    //{
                    //    if (IsRunning && _server != null)
                    //        _server.BeginReceive(new AsyncCallback(ReceiveDataAsync), udpState);
                    //}
                }
            }
            catch (Exception exception)
            {
                RaiseNetError(udpState, exception);
            }
            finally
            {
                lock (this)
                {
                    if (IsRunning && _server != null)
                    {
                        udpReceiveState = new AsyncUDPState();
                        _server.BeginReceive(ReceiveDataAsync, udpReceiveState);
                    }
                }
            }
        }