示例#1
0
 /// <summary>
 ///   处理接收到的数据
 /// </summary>
 /// <param name="args">异步SOCKET事件</param>
 private void ProcessRecv(SocketAsyncEventArgs args)
 {
     if (args.BytesTransferred == 0 || args.SocketError != SocketError.Success)
     {
         Stop();
         return;
     }
     try
     {
         int    count   = args.BytesTransferred;
         string content = Encoding.UTF8.GetString(args.Buffer, 0, count);
         CommonBoradcastProtocol obj = JsonConvert.DeserializeObject <CommonBoradcastProtocol>(content);
         //discard current boradcast object directly when it was an illegal object.
         if (string.IsNullOrEmpty(obj.Key))
         {
             return;
         }
         //dispatch it.
         Action <CommonBoradcastProtocol> callback;
         if (!_callbacks.TryGetValue(obj.Key, out callback))
         {
             _tracing.Warn("#We had to discared current boradcast object, because of it hasn't any dispatcher in there.");
             return;
         }
         callback(obj);
     }
     catch (System.Exception ex) { _tracing.Error(ex, null); }
     finally { StartRecv(args); }
 }
示例#2
0
        /// <summary>
        ///   发送一个消息
        /// </summary>
        /// <exception cref="ArgumentNullException">参数不能为空</exception>
        /// <exception cref="ArgumentException">字段不能没有值</exception>
        /// <exception cref="Exception">内部无法发送出任何数据到目标网络</exception>
        public void Send(CommonBoradcastProtocol obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }
            if (string.IsNullOrEmpty(obj.Key))
            {
                throw new ArgumentException("#Key cannot be null or empty.");
            }
            if (string.IsNullOrEmpty(obj.Environment))
            {
                throw new ArgumentException("#Environment cannot be null or empty.");
            }
            string content = JsonConvert.SerializeObject(obj);

            if (_socket.SendTo(Encoding.UTF8.GetBytes(content), _broadcastIep) <= 0)
            {
                throw new System.Exception("#Sadly, We had sent nothing to destination network.");
            }
        }