Exemple #1
0
        private void ClearSocketSession(object state)
        {
            if (Monitor.TryEnter(state))
            {
                try
                {
                    ICollection <IChannel> socketChannels = this.ChannelManager.GetChannels(CommunicateType.NET);

                    if (socketChannels == null || socketChannels.Count <= 0)
                    {
                        return;
                    }

                    DateTime now = DateTime.Now;

                    IEnumerable <IChannel> timeoutSessions = socketChannels.Where(c => (now - ((ISocketSession)c).LastActiveTime).Seconds > ServerConfig.ClearSocketSessionTimeOut);

                    System.Threading.Tasks.Parallel.ForEach(timeoutSessions, c =>
                    {
                        ISocketSession s = ((ISocketSession)c);
                        Logger.Info(true, String.Format("网络连接超时:{0}, 开始时间: {1}, 最后激活时间:{2}!", now.Subtract(s.LastActiveTime).TotalSeconds, s.StartTime, s.LastActiveTime));
                        RemoveTcpSocketSession(s);
                    });
                }
                catch (Exception ex)
                {
                    this.Logger.Error(true, ex.Message);
                }
                finally
                {
                    Monitor.Exit(state);
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// 分析Redis缓存中packetKey的数据包并处理
        /// </summary>
        private void AnalyticMessage(ISocketSession session)
        {
            //StringLocker.Run("packetKey",)
            //{
            string str = "";
            //var packetList = redis.ListRange<string>("packetKey", 0, 10, DataType.Protobuf);//每次取10条数据
            var packetList = redis.Smember <DataPacket>("packetKey", DataType.Protobuf);

            packetList.ForEach(async p =>
            {
                //var packet = Formatter.Deserialize<DataPacket>(p);//反序列化
                var responseMessage = await ApiProcessor.Process(p.Data);
                str = responseMessage == null ? "" : responseMessage.ToString();
            });

            session.Send(str);
            //StringLocker.Run("device", () => Task.Factory.StartNew(() => ApiProcessor.ProcessRedisCache()));
            //Thread.Sleep(50);//等待数据处理完毕后,在处理缓存
            if (_processRedisTimer == null)
            {
                _processRedisTimer = new TimerX(obj => ApiProcessor.ProcessRedisCache(), null, 1000, 5000);
            }
            //Task.Factory.StartNew(() => ApiProcessor.ProcessRedisCache());//处理缓存
            //}
        }
        protected bool InternalTrySend(ISocketSession session, IProtoHandler protoHandler, ArraySegment<byte> segment)
        {
            if (!session.TrySend(segment))
                return false;

            return true;
        }
        /// <summary>已重载。</summary>
        /// <param name="session"></param>
        protected override INetSession OnNewSession(ISocketSession session)
        {
            WriteLog("Chargen {0} OnAccept", session.Remote);

            // 如果没有远程地址,或者远程地址是广播地址,则跳过。否则会攻击广播者。
            // Tcp的该属性可能没值,可以忽略
            var remote = session.Remote.EndPoint;

            if (remote != null && remote.Address.IsAny())
            {
                return(null);
            }

            // 使用多线程
            var thread = new Thread(LoopSend)
            {
                Name         = "Chargen.LoopSend",
                IsBackground = true
            };

            //thread.Priority = ThreadPriority.Lowest;
            thread.Start(session);

            //return base.OnNewSession(session);
            return(null);
        }
Exemple #5
0
        /// <summary>
        /// Creates the app session.
        /// </summary>
        /// <param name="socketSession">The socket session.</param>
        /// <returns></returns>
        IAppSession IAppServer.CreateAppSession(ISocketSession socketSession)
        {
            if (!ExecuteConnectionFilters(socketSession.RemoteEndPoint))
            {
                return(NullAppSession);
            }

            var appSession = new TAppSession();

            if (!RegisterSession(socketSession.SessionID, appSession))
            {
                return(NullAppSession);
            }

            appSession.Initialize(this, socketSession, RequestFilterFactory.CreateFilter(this, socketSession));
            socketSession.Closed += OnSocketSessionClosed;

            if (Logger.IsInfoEnabled)
            {
                Logger.InfoFormat("A new session connected!");
            }

            OnNewSessionConnected(appSession);

            return(appSession);
        }
Exemple #6
0
        /// <summary>收到连接时,建立会话,并挂接数据接收和错误处理事件</summary>
        /// <param name="session"></param>
        protected virtual INetSession OnNewSession(ISocketSession session)
        {
            Interlocked.Increment(ref _SessionCount);
            session.OnDisposed += (s, e2) => Interlocked.Decrement(ref _SessionCount);

            var ns = CreateSession(session);

            // sessionID变大后,可能达到最大值,然后变为-1,再变为0,所以不用担心
            //ns.ID = ++sessionID;
            // 网络会话改为原子操作,避免多线程冲突
            ns.ID      = Interlocked.Increment(ref sessionID);
            ns.Host    = this;
            ns.Server  = session.Server;
            ns.Session = session;
            if (ns is NetSession)
            {
                (ns as NetSession).Log = SessionLog ?? Log;
            }

            if (UseSession)
            {
                AddSession(ns);
            }

            session.Received += OnReceived;
            session.Error    += OnError;

            // 开始会话处理
            ns.Start();

            return(ns);
        }
Exemple #7
0
        protected IAppSession CreateSession(Socket client, ISocketSession session)
        {
            if (m_SendTimeOut > 0)
            {
                client.SendTimeout = m_SendTimeOut;
            }

            if (m_ReceiveBufferSize > 0)
            {
                client.ReceiveBufferSize = m_ReceiveBufferSize;
            }

            if (m_SendBufferSize > 0)
            {
                client.SendBufferSize = m_SendBufferSize;
            }

            if (!Platform.SupportSocketIOControlByCodeEnum)
            {
                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_KeepAliveOptionValues);
            }
            else
            {
                client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, m_KeepAliveOptionOutValues);
            }

            client.NoDelay     = m_NoDelay;
            client.LingerState = new LingerOption(enable: false, seconds: 0); // socket 종료하면 즉시 제거한다.
            //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); //닷넷코어에서 사용 불가

            return(this.AppServer.CreateAppSession(session));
        }
Exemple #8
0
        public IChannel GetChannel(string ioPara1, int ioPara2, CommunicateType comType)
        {
            IChannel channel = null;

            foreach (KeyValuePair <string, IChannel> c in _Channels)
            {
                if (c.Value.CommunicationType == comType)
                {
                    ISocketSession socketSession = (ISocketSession)c.Value;
                    if (socketSession.RemoteIP == ioPara1 && socketSession.RemotePort == ioPara2)
                    {
                        channel = c.Value;
                        break;
                    }
                }
                else if (c.Value.CommunicationType == comType)
                {
                    IComSession comSession = (IComSession)c.Value;
                    if (ComUtils.PortToString(comSession.Port) == ioPara1 && comSession.Baud == ioPara2)
                    {
                        channel = c.Value;
                        break;
                    }
                }
            }
            return(channel);
        }
Exemple #9
0
        /// <summary>已重载。</summary>
        /// <param name="session"></param>
        /// <param name="stream"></param>
        protected override void OnReceive(ISocketSession session, Stream stream)
        {
            if (stream.Length == 0)
            {
                return;
            }

            var p = stream.Position;

            if (stream.Length > 100)
            {
                WriteLog("Echo {0} [{1}]", session.Remote, stream.Length);
            }
            else
            {
                WriteLog("Echo {0} [{1}] {2}", session.Remote, stream.Length, stream.ToStr());
            }

            //Send(e.Socket, e.Buffer, e.Offset, stream.Length, e.RemoteEndPoint);
            //session.Send(e.Buffer, e.Offset, stream.Length, e.RemoteEndPoint);
            //session.Send(e.Buffer, e.Offset, stream.Length);
            stream.Position = p;
            //session.Send(stream);
            session.SendAsync(stream.ReadBytes());
        }
        protected IAppSession CreateSession(Socket client, ISocketSession session)
        {
            if (m_SendTimeOut > 0)
            {
                client.SendTimeout = m_SendTimeOut;
            }

            if (m_ReceiveBufferSize > 0)
            {
                client.ReceiveBufferSize = m_ReceiveBufferSize;
            }

            if (m_SendBufferSize > 0)
            {
                client.SendBufferSize = m_SendBufferSize;
            }

            if (!Platform.SupportSocketIOControlByCodeEnum)
            {
                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_KeepAliveOptionValues);
            }
            else
            {
                client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, m_KeepAliveOptionOutValues);
            }

            client.NoDelay = true;
            client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            return(this.AppServer.CreateAppSession(session));
        }
Exemple #11
0
        void SessionClosed(ISocketSession session, CloseReason reason)
        {
            var socketSession = session as IAsyncSocketSessionBase;

            if (socketSession == null)
            {
                return;
            }

            var proxy = socketSession.SocketAsyncProxy;

            proxy.Reset();

            var serverState = AppServer.State;
            var pool        = this.m_ReadWritePool;

            if (pool == null || serverState == ServerState.Stopping || serverState == ServerState.NotStarted)
            {
                if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
                {
                    proxy.SocketEventArgs.Dispose();
                }
                return;
            }

            if (proxy.OrigOffset != proxy.SocketEventArgs.Offset)
            {
                proxy.SocketEventArgs.SetBuffer(proxy.OrigOffset, AppServer.Config.ReceiveBufferSize);
            }

            pool.Push(proxy);
        }
        protected ISocketSession RegisterSession(Socket client, ISocketSession session)
        {
            if (m_SendTimeOut > 0)
                client.SendTimeout = m_SendTimeOut;

            if (m_ReceiveBufferSize > 0)
                client.ReceiveBufferSize = m_ReceiveBufferSize;

            if (m_SendBufferSize > 0)
                client.SendBufferSize = m_SendBufferSize;

            if(!Platform.SupportSocketIOControlByCodeEnum)
                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            else
                client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, null);

            client.NoDelay = true;
            client.UseOnlyOverlappedIO = true;
            client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            IAppSession appSession = this.AppServer.CreateAppSession(session);

            if (appSession == null)
                return null;

            return session;
        }
Exemple #13
0
        /// <summary>
        /// 运行调度设备
        /// </summary>
        /// <param name="dev"></param>
        private void RunDevice(IRunDevice dev)
        {
            ISocketSession io = null;

            try
            {
                io = (ISocketSession)this.Server.ChannelManager.GetChannel(dev.DeviceParameter.NET.RemoteIP, CommunicateType.NET);
                if (io != null)
                {
                    dev.Run(io);
                }
                else
                {
                    dev.Run((IChannel)null);   //如果没有找到连接,则传递空值
                    //没有找到可用的设备,加延时,局免循环过快。
                    System.Threading.Thread.Sleep(1000);
                }
            }
            catch (SocketException ex)
            {
                this.Server.Logger.Error(true, "网络控制器", ex);
            }
            catch (Exception ex)
            {
                this.Server.Logger.Error(true, "网络控制器", ex);
            }
        }
Exemple #14
0
        public void Process(ISocketSession session, ReceivedEventArgs e)
        {
            string package = e.ToStr();
            var    client  = session;

            var id = Guid.NewGuid().ToString();

            //缓存客户端会话
            RemoteSessionHelper.RemoteSessionCache.AddOrUpdate(id,
                                                               key => null,
                                                               (key, oldValue) =>
            {
                if (!oldValue.Disposed)
                {
                    oldValue.Dispose();
                }
                return(client);
            });
            //将数据包封装后放到redis中
            var dataPackage = new DataPacket {
                Id = id, Data = package, Date = DateTime.Now
            };                                                                                 //对当前接受数据进行封装

            _redisClient.ListAdd(RedisKeyString.PackageList, dataPackage, DataType.Protobuf);
            //数据包处理结束
        }
        public virtual bool TrySend(ISocketSession session, ArraySegment<byte> data)
        {
            if (!session.CanSend())
                return false;

            return InternalTrySend(session, data);
        }
 /// <summary>Add or update session
 /// </summary>
 public void UpdateSession(ISocketSession socketSession)
 {
     if (_sessionDict.TryGetValue(socketSession.SessionId, out ISocketSession oldSession))
     {
         _sessionDict.TryUpdate(socketSession.SessionId, socketSession, oldSession);
     }
 }
        public virtual bool TrySend(ISocketSession session, IList<ArraySegment<byte>> segments)
        {
            if (!session.CanSend())
                return false;

            return InternalTrySend(session, segments);
        }
        protected void InternalSend(ISocketSession session, IList<ArraySegment<byte>> segments)
        {
            if (!session.CanSend())
                return;

            if (InternalTrySend(session, segments))
                return;

            var sendTimeOut = m_SendTimeOut;

            //Don't retry, timeout directly
            if (sendTimeOut < 0)
            {
                throw new TimeoutException("The sending attempt timed out");
            }

            var timeOutTime = sendTimeOut > 0 ? DateTime.Now.AddMilliseconds(sendTimeOut) : DateTime.Now;

            var spinWait = new SpinWait();

            while (session.CanSend())
            {
                spinWait.SpinOnce();

                if (InternalTrySend(session, segments))
                    return;

                //If sendTimeOut = 0, don't have timeout check
                if (sendTimeOut > 0 && DateTime.Now >= timeOutTime)
                {
                    throw new TimeoutException("The sending attempt timed out");
                }
            }
        }
Exemple #19
0
 /// <summary>已重载。</summary>
 /// <param name="session"></param>
 /// <param name="stream"></param>
 protected override void OnReceive(ISocketSession session, Stream stream)
 {
     if (stream.Length > 0)
     {
         StreamHandler.Process(StreamHandlerName, stream);
     }
 }
Exemple #20
0
        static void TestSend()
        {
            var            ip      = NetHelper.ParseAddress(Host);
            ISocketSession session = NetService.CreateSession(new NetUri(string.Format("Tcp://{0}:{1}", ip, Port)));

            try
            {
                session.Send(data);
                Interlocked.Add(ref SendBytes, data.Length);
                Interlocked.Increment(ref SendCounts);
                //WriteLine(string.Format("{0} 发送{1}字节,共{2}字节", DateTime.Now, data.Length, SendBytes));
                var receive = session.Receive();
                if (receive != null)
                {
                    Interlocked.Add(ref ReceiveBytes, receive.Length);
                    Interlocked.Increment(ref ReceiveCounts);
                }

                //WriteLine(string.Format("共接收{0}字节", ReceiveBytes));
            }
            catch (Exception ex)
            {
                WriteLine(ex.ToString());
            }
            session.Dispose();
        }
Exemple #21
0
        protected bool InternalTrySend(ISocketSession session, IList <ArraySegment <byte> > segments)
        {
            if (!session.TrySend(segments))
            {
                return(false);
            }

            return(true);
        }
Exemple #22
0
        public virtual bool TrySend(ISocketSession session, ArraySegment <byte> data)
        {
            if (!session.CanSend())
            {
                return(false);
            }

            return(InternalTrySend(session, data));
        }
Exemple #23
0
        public virtual bool TrySend(ISocketSession session, IList <ArraySegment <byte> > segments)
        {
            if (!session.CanSend())
            {
                return(false);
            }

            return(InternalTrySend(session, segments));
        }
Exemple #24
0
        /// <summary>已重载。</summary>
        /// <param name="session"></param>
        /// <param name="stream"></param>
        protected override void OnReceive(ISocketSession session, Stream stream)
        {
            if (stream.Length == 0) return;

            if (stream.Length > 100)
                WriteLog("Chargen {0} [{1}]", session.Remote, stream.Length);
            else
                WriteLog("Chargen {0} [{1}] {2}", session.Remote, stream.Length, stream.ToStr());
        }
Exemple #25
0
 private void OnSocketSessionClosed(ISocketSession session, CloseReason reason)
 {
     Logger.Info(string.Format("This session was closed for {0}!", reason));
     if (m_SessionDict.TryGetValue(session.SessionID, out AppSession appSession))
     {
         appSession.Connected = false;
         OnSessionClosed(appSession, reason);
     }
 }
 /// <summary>
 /// Initializes the specified app session by AppServer and SocketSession.
 /// </summary>
 /// <param name="appServer">The app server.</param>
 /// <param name="socketSession">The socket session.</param>
 /// <param name="requestFilter">The request filter.</param>
 public virtual void Initialize(IAppServer <TAppSession, TRequestInfo> appServer, ISocketSession socketSession, IRequestFilter <TRequestInfo> requestFilter)
 {
     AppServer       = (AppServerBase <TAppSession, TRequestInfo>)appServer;
     SocketSession   = socketSession;
     SessionID       = socketSession.SessionID;
     m_Connected     = true;
     m_RequestFilter = requestFilter;
     OnInit();
 }
Exemple #27
0
 /// <summary>
 /// Initializes the specified app session by AppServer and SocketSession.
 /// </summary>
 /// <param name="appServer">The app server.</param>
 /// <param name="socketSession">The socket session.</param>
 public virtual void Initialize(IAppServer <TAppSession, TCommandInfo> appServer, ISocketSession socketSession)
 {
     AppServer     = appServer;
     SocketSession = socketSession;
     SessionID     = socketSession.SessionID;
     IdentityKey   = socketSession.IdentityKey;
     Status        = SessionStatus.Healthy;
     OnInit();
 }
Exemple #28
0
 public virtual void Initialize(IAppServer <TAppSession> appServer, ISocketSession socketSession)
 {
     AppContext            = new TSocketContext();
     AppServer             = appServer as TAppServer;
     SocketSession         = socketSession;
     SocketSession.Closed += new EventHandler <SocketSessionClosedEventArgs>(SocketSession_Closed);
     SessionID             = socketSession.SessionID;
     OnInit();
 }
Exemple #29
0
        /// <summary>
        /// Called when [socket session closed].
        /// </summary>
        /// <param name="session">The socket session.</param>
        /// <param name="reason">The reason.</param>
        private void OnSocketSessionClosed(ISocketSession session, CloseReason reason)
        {
            if (Logger.IsInfoEnabled)
            {
                Logger.Info(session, "This session was closed!");
            }

            OnSessionClosed((TAppSession)session.AppSession, reason);
        }
Exemple #30
0
        /// <summary>
        /// Called when [socket session closed].
        /// </summary>
        /// <param name="session">The socket session.</param>
        /// <param name="reason">The reason.</param>
        private void OnSocketSessionClosed(ISocketSession session, CloseReason reason)
        {
            if (Logger.IsInfoEnabled)
            {
                Logger.Info(session, string.Format("This session was closed for {0}!", reason));
            }

            OnSessionClosed((TAppSession)session.AppSession, reason);
        }
Exemple #31
0
 internal void Initialize(AppServer appServer, ISocketSession socketSession)
 {
     AppServer       = appServer;
     SocketSession   = socketSession;
     SessionID       = socketSession.SessionID;
     m_Connected     = true;
     m_ReceiveFilter = new TerminatorReceiveFilter(new byte[] { (byte)'\r', (byte)'\n' });
     socketSession.Initialize(this);
 }
        protected bool InternalTrySend(ISocketSession session, IProtoHandler protoHandler, ArraySegment <byte> segment)
        {
            if (!session.TrySend(segment))
            {
                return(false);
            }

            return(true);
        }
Exemple #33
0
        /// <summary>
        /// 发送内部通信
        /// </summary>
        /// <param name="Param"></param>
        /// <param name="Session"></param>
        public static void SendInternalInfo(SocketSerializeData SerializeData, ISocketSession Session = null)
        {
            ISocketResult Param = new SocketResultDefault()
            {
                Router = SerializeData.Route, SocketJsonData = SerializeData.Providor?.ToJson()
            };

            SocketClient.Send(SocketMiddleData.Middle(SendTypeEnum.InternalInfo, Param, Session, SocketConstConfig.ClientPort).ToJson());
        }
        public virtual bool TrySend(ISocketSession session, IProtoHandler protoHandler, ArraySegment <byte> data)
        {
            if (!session.CanSend() || (protoHandler != null && !protoHandler.CanSend()))
            {
                return(false);
            }

            return(InternalTrySend(session, protoHandler, data));
        }
        public bool ExecuteHandler(IMsg requestInfo, ISocketSession session)
        {
            foreach (var s in session.GetAllSessionId())
            {
                session.SendAsync(s, requestInfo.Data, requestInfo.RemoteIpEndPoint);
            }

            return true;
        }
Exemple #36
0
        /// <summary>创建会话</summary>
        /// <param name="session"></param>
        /// <returns></returns>
        protected virtual INetSession CreateSession(ISocketSession session)
        {
            var ns = new NetSession();

            (ns as INetSession).Host = this;
            ns.Server  = session.Server;
            ns.Session = session;

            return(ns);
        }
 public bool ExecuteHandler(IMsg requestInfo, ISocketSession session)
 {
     byte[] b= new byte[2048];
     for(int i=0;i< 2048; i++)
     {
         b[i] = 127; 
     }
     session.SendAsync(requestInfo.Data, requestInfo.RemoteIpEndPoint);
     return true;
 }
Exemple #38
0
        void session_Closed(ISocketSession session, CloseReason reason)
        {
            IAsyncSocketSessionBase socketSession = session as IAsyncSocketSessionBase;

            if (socketSession != null && this.m_ReadWritePool != null)
            {
                socketSession.SocketAsyncProxy.Reset();
                this.m_ReadWritePool.Push(socketSession.SocketAsyncProxy);
            }
        }
Exemple #39
0
        /// <summary>已重载。</summary>
        /// <param name="session"></param>
        protected override INetSession OnNewSession(ISocketSession session)
        {
            WriteLog("Chargen {0} OnAccept", session.Remote);

            // 如果没有远程地址,或者远程地址是广播地址,则跳过。否则会攻击广播者。
            // Tcp的该属性可能没值,可以忽略
            var remote = session.Remote.EndPoint;
            if (remote != null && remote.Address.IsAny()) return null;

            // 使用多线程
            var thread = new Thread(LoopSend);
            thread.Name = "Chargen.LoopSend";
            thread.IsBackground = true;
            //thread.Priority = ThreadPriority.Lowest;
            thread.Start(session);

            //return base.OnNewSession(session);
            return null;
        }
        protected IAppSession CreateSession(Socket client, ISocketSession session)
        {
            if (m_SendTimeOut > 0)
                client.SendTimeout = m_SendTimeOut;

            if (m_ReceiveBufferSize > 0)
                client.ReceiveBufferSize = m_ReceiveBufferSize;

            if (m_SendBufferSize > 0)
                client.SendBufferSize = m_SendBufferSize;

            if (!Platform.SupportSocketIOControlByCodeEnum)
                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_KeepAliveOptionValues);
            else
                client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, m_KeepAliveOptionOutValues);

            client.NoDelay = true;
            client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            return this.AppServer.CreateAppSession(session);
        }
 public override void Send(ISocketSession session, IList<ArraySegment<byte>> segments)
 {
     base.Send(session, m_Encoder.EncodeData(segments));
 }
 public override bool TrySend(ISocketSession session, ArraySegment<byte> data)
 {
     return base.TrySend(session, m_Encoder.EncodeData(data));
 }
 public override bool TrySend(ISocketSession session, IList<ArraySegment<byte>> segments)
 {
     return base.TrySend(session, m_Encoder.EncodeData(segments));
 }
 void SessionClosed(ISocketSession session, CloseReason reason)
 {
     Interlocked.Decrement(ref m_TotalConnections);
 }
 public virtual void Send(ISocketSession session, IList<ArraySegment<byte>> segments)
 {
     InternalSend(session, segments);
 }
Exemple #46
0
        void SessionClosed(ISocketSession session, CloseReason reason)
        {
            var socketSession = session as IAsyncSocketSessionBase;
            if (socketSession == null)
                return;

            var proxy = socketSession.SocketAsyncProxy;
            proxy.Reset();

            var serverState = AppServer.State;
            var pool = this.m_ReadWritePool;

            if (pool == null || serverState == ServerState.Stopping || serverState == ServerState.NotStarted)
            {
                if(!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload())
                    proxy.SocketEventArgs.Dispose();
                return;
            }

            if (proxy.OrigOffset != proxy.SocketEventArgs.Offset)
            {
                proxy.SocketEventArgs.SetBuffer(proxy.OrigOffset, AppServer.Config.ReceiveBufferSize);
            }

            pool.Push(proxy);
        }
        public virtual bool TrySend(ISocketSession session, IProtoHandler protoHandler, ArraySegment<byte> data)
        {
            if (!session.CanSend() || (protoHandler != null && !protoHandler.CanSend()))
                return false;

            return InternalTrySend(session, protoHandler, data);
        }
Exemple #48
0
        /// <summary>为指定地址创建会话。对于无连接Socket,必须指定远程地址;对于有连接Socket,指定的远程地址将不起任何作用</summary>
        /// <param name="remoteEP"></param>
        /// <returns></returns>
        public override ISocketSession CreateSession(IPEndPoint remoteEP = null)
        {
            var socket = Client;
            if (!socket.Connected)
            {
                if (remoteEP == null) throw new ArgumentNullException("remoteEP", "未连接Udp必须指定远程地址!");

                return new UdpSession(this, remoteEP);
            }
            else
            {
                // 已连接。返回已有的
                if (_session == null) _session = new UdpSession(this, remoteEP);
                return _session;
            }
        }
Exemple #49
0
        void Send(ISocketSession session)
        {
            Int32 startIndex = Index++;
            if (Index >= Length) Index = 0;

            Byte[] buffer = new Byte[Length];

            // 产生数据
            for (int i = 0; i < buffer.Length; i++)
            {
                Int32 p = startIndex + i;
                if (p >= buffer.Length) p -= buffer.Length;
                buffer[p] = (Byte)(i + 32);
            }

            session.Send(buffer);
        }
Exemple #50
0
 /// <summary>已重载。</summary>
 /// <param name="session"></param>
 /// <param name="stream"></param>
 protected override void OnReceive(ISocketSession session, Stream stream)
 {
     if (stream.Length > 0) StreamHandler.Process(StreamHandlerName, stream);
 }
Exemple #51
0
 /// <summary>创建会话</summary>
 /// <param name="session"></param>
 /// <returns></returns>
 protected override INetSession CreateSession(ISocketSession session)
 {
     return new Session();
 }
 public virtual void Send(ISocketSession session, ArraySegment<byte> data)
 {
     InternalSend(session, new ArraySegment<byte>[] { data });
 }
 public override void Send(ISocketSession session, ArraySegment<byte> data)
 {
     base.Send(session, m_Encoder.EncodeData(data));
 }
 public virtual void Send(ISocketSession session, IProtoHandler protoHandler, ArraySegment<byte> data)
 {
     InternalSend(session, protoHandler, new ArraySegment<byte>[] { data });
 }
 public SessionCreatedEventArgs(ISocketSession session)
 {
     Session = session;
 }
Exemple #56
0
 void session_Closed(ISocketSession session, CloseReason reason)
 {
     IAsyncSocketSessionBase socketSession = session as IAsyncSocketSessionBase;
     if (socketSession != null && this.m_ReadWritePool != null)
     {
         socketSession.SocketAsyncProxy.Reset();
         this.m_ReadWritePool.Push(socketSession.SocketAsyncProxy);
     }
 }
 public override void Send(ISocketSession session, IProtoHandler protoHandler, IList<ArraySegment<byte>> segments)
 {
     base.Send(session, protoHandler, protoHandler.DataEncoder.EncodeData(segments));
 }
        protected bool InternalTrySend(ISocketSession session, IList<ArraySegment<byte>> segments)
        {
            if (!session.TrySend(segments))
                return false;

            return true;
        }
        void SessionClosed(ISocketSession session, CloseReason reason)
        {
            var socketSession = session as IAsyncSocketSessionBase;

            if (socketSession != null && this.m_ReadWritePool != null)
            {
                var proxy = socketSession.SocketAsyncProxy;
                proxy.Reset();

                if (proxy.OrigOffset != proxy.SocketEventArgs.Offset)
                {
                    proxy.SocketEventArgs.SetBuffer(proxy.OrigOffset, AppServer.Config.ReceiveBufferSize);
                }

                if (m_ReadWritePool != null)
                    m_ReadWritePool.Push(proxy);
            }
        }
 public override bool TrySend(ISocketSession session, IProtoHandler protoHandler, IList<ArraySegment<byte>> segments)
 {
     return base.TrySend(session, protoHandler, protoHandler.DataEncoder.EncodeData(segments));
 }