Exemplo n.º 1
0
 /// <summary>
 /// 异步运行接受消息回调
 /// </summary>
 /// <param name="msg"></param>
 void ReceiveCallbackAsync(SocketSession session, string msg)
 {
     if (ReceiveCallback == null)
     {
         return;
     }
     Task.Run(() =>
     {
         try
         {
             ReceiveCallback(session, msg);
         }
         catch (Exception ex)
         {
             Log4netHelper.Fatal($"服务端接收到消息但执行ReceiveCallback异常:{msg}", ex);
         }
     });
 }
Exemplo n.º 2
0
        /// <summary>
        /// 接受连接
        /// </summary>
        /// <param name="ar"></param>
        private void BeginAcceptConnection(IAsyncResult ar)
        {
            if (this.IsDisposable)
            {
                return;
            }
            var socket         = SOCKET_SERVER.EndAccept(ar);
            var remoteEndPoint = ((System.Net.IPEndPoint)socket.RemoteEndPoint);

            Log4netHelper.Debug($"{remoteEndPoint.Address.ToString()}连接到了本服务端");
            var session = new SocketSession(socket)
            {
                Id              = Guid.NewGuid().ToString(),
                RemoteEndPoint  = socket.RemoteEndPoint,
                ReceiveCallback = (obj, msg) =>
                {
                    try
                    {
                        ReceiveEvent(obj, msg);
                    }
                    catch (Exception ex)
                    {
                        Log4netHelper.Fatal($"服务端在执行ReceiveEvent事件时发生异常{Environment.NewLine}消息内容{msg}{Environment.NewLine}会话{JsonHelper.SerializeObject(obj)}", ex);
                    }
                },
                DisposeCallback = (obj) =>
                {
                    SESSIONS.Remove(obj);
                },
            };

            session.Start();
            SESSIONS.Add(session);
            SOCKET_SERVER.BeginAccept(new AsyncCallback(BeginAcceptConnection), null);
            AcceptConnectionEvent(session, null);
        }