internal TcpSocketSessionProviderHandle(
            SessionProviderOptions options,
            OnSessionNotify <SessionCompletedNotify, SessionProviderContext> onSessionNotifyProc)
            : base(onSessionNotifyProc)
        {
            _options = options;

            var serverConfig = new TcpSocketSaeaServerConfiguration();

            serverConfig.AppKeepAlive = true;
            serverConfig.CompressTransferFromPacket = false;
            serverConfig.PendingConnectionBacklog   = options.PendingConnectionBacklog;

            _server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig, (notify, session) =>
            {
                switch (notify)
                {
                case TcpSocketCompletionNotify.OnConnected:

                    var sessionBased = new TcpSocketSessionBased(session);

                    session.AppTokens = new object[]
                    {
                        sessionBased
                    };

                    _onSessionNotifyProc(SessionCompletedNotify.OnConnected, sessionBased);

                    break;

                case TcpSocketCompletionNotify.OnSend:
                    _onSessionNotifyProc(SessionCompletedNotify.OnSend, session.AppTokens[0] as SessionProviderContext);
                    break;

                case TcpSocketCompletionNotify.OnDataReceiveing:
                    _onSessionNotifyProc(SessionCompletedNotify.OnRecv, session.AppTokens[0] as SessionProviderContext);
                    break;

                case TcpSocketCompletionNotify.OnDataReceived:
                    _onSessionNotifyProc(SessionCompletedNotify.OnReceived, session.AppTokens[0] as SessionProviderContext);
                    break;

                case TcpSocketCompletionNotify.OnClosed:
                    _onSessionNotifyProc(SessionCompletedNotify.OnClosed, session.AppTokens[0] as SessionProviderContext);
                    break;

                default:
                    break;
                }
            });
        }
示例#2
0
        public bool StartService()
        {
            var serverConfig = new TcpSocketSaeaServerConfiguration();

            serverConfig.ReuseAddress             = false;
            serverConfig.KeepAlive                = true;
            serverConfig.KeepAliveInterval        = 5000;
            serverConfig.KeepAliveSpanTime        = 1000;
            serverConfig.PendingConnectionBacklog = 0;

            var ipe = new IPEndPoint(IPAddress.Parse(ApplicationConfiguartion.LocalAddress), ApplicationConfiguartion.ServicePort);

            _tcpSaeaServer = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Full, serverConfig, (notify, session) =>
            {
                switch (notify)
                {
                case TcpSocketCompletionNotify.OnConnected:

                    ApportionDispatcher apportionDispatcher        = new ApportionDispatcher();
                    apportionDispatcher.ApportionTypeHandlerEvent += ApportionTypeHandlerEvent;
                    apportionDispatcher.SetSession(session);

                    break;

                case TcpSocketCompletionNotify.OnSend:
                    break;

                case TcpSocketCompletionNotify.OnDataReceiveing:
                    this.OnDataReceiveingHandler(session);
                    break;

                case TcpSocketCompletionNotify.OnClosed:
                    this.OnClosedHandler(session);
                    break;

                default:
                    break;
                }
            });
            return(true);
        }
        internal TcpSocketSessionProvider(SessionProviderOptions options)
        {
            ApplicationConfiguartion.SetOptions(options);
            var serverConfig = new TcpSocketSaeaServerConfiguration();

            serverConfig.AppKeepAlive = true;
            serverConfig.CompressTransferFromPacket = false;
            serverConfig.PendingConnectionBacklog   = ApplicationConfiguartion.Options.PendingConnectionBacklog;

            _server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig, (notify, session) =>
            {
                switch (notify)
                {
                case TcpSessionNotify.OnConnected:

                    SessionProviderContext sessionBased = new TcpSocketSessionContext(session);
                    this.SessionNotify(sessionBased, TcpSessionNotify.OnConnected);
                    break;

                case TcpSessionNotify.OnSend:
                    this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnSend);
                    break;

                case TcpSessionNotify.OnDataReceiveing:
                    this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnDataReceiveing);
                    break;

                case TcpSessionNotify.OnDataReceived:
                    this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnDataReceived);
                    break;

                case TcpSessionNotify.OnClosed:
                    this.SessionNotify(session.AppTokens.First().ConvertTo <SessionProviderContext>(), TcpSessionNotify.OnClosed);
                    break;

                default:
                    break;
                }
            });
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //模式说明
            //Full模式:仅接收发送数据(高性能的数据接收模型,可启用TcpKeepAlive选项)注:数据压缩丶AppKeepAlive选项在Full模式下启用无效
            //Pack模式:自动处理分包(高性能的数据接收模型,自动处理分包,可启用数据压缩丶应用层心跳包丶TcpKeepAlive选项)


            //设置在Socket初始化后无法修改
            TcpSocketSaeaClientConfiguration clientConfig = new TcpSocketSaeaClientConfiguration();

            clientConfig.KeepAlive    = false;
            clientConfig.AppKeepAlive = true;
            client = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, Client_CompletetionNotify);



            TcpSocketSaeaServerConfiguration serverConfig = new TcpSocketSaeaServerConfiguration();

            serverConfig.KeepAlive    = false;
            serverConfig.AppKeepAlive = true;
            server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig, Server_CompletetionNotify);
        }
        protected override void OnStart(string[] args)
        {
            var serverConfig = new TcpSocketSaeaServerConfiguration();

            serverConfig.AppKeepAlive             = true;
            serverConfig.PendingConnectionBacklog = 0;
            var trunkService = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Packet, serverConfig,
                                                                   (notity, session) =>
            {
                switch (notity)
                {
                case TcpSessionNotify.OnConnected:
                    LogHelper.DebugWriteLog("OnConnected");
                    break;

                case TcpSessionNotify.OnSend:
                    break;

                case TcpSessionNotify.OnDataReceiveing:
                    break;

                case TcpSessionNotify.OnDataReceived:
                    _handlerBinder.InvokePacketHandler(session, session.CompletedBuffer.GetMessageHead <TrunkMessageHead>(), this);
                    break;

                case TcpSessionNotify.OnClosed:
                    this.SessionClosedHandler(session);
                    break;

                default:
                    break;
                }
            });

            bool completed = false;

            for (int trycount = 0; trycount < 100; trycount++)
            {
                try
                {
                    _port = 10000 + trycount;
                    var ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), _port);
                    trunkService.Listen(ipEndPoint);
                    completed = true;
                    break;
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorByCurrentMethod("trunkService open listen exception:" + ex.Message);
                }
                completed = false;
                Thread.Sleep(1000);
            }
            if (!completed)
            {
                LogHelper.WriteErrorByCurrentMethod("listen all tcp port not completed,please check!");
                Environment.Exit(0);//监听所有端口失败
            }


            // Obtain session ID for active session.
            uint dwSessionId = Kernel32.WTSGetActiveConsoleSessionId();

            // Check for RDP session.  If active, use that session ID instead.
            var rdpSessionID = Win32Interop.GetRDPSession();

            if (rdpSessionID > 0)
            {
                dwSessionId = rdpSessionID;
            }
            this.CreateProcessAsUser(dwSessionId, true);
            ThreadHelper.CreateThread(() =>
            {
                while (_isRun)
                {
                    lock (_lock)
                        for (int i = 0; i < _userProcessSessionIdList.Count; i++)
                        {
                            var token = _userProcessSessionIdList[i];
                            if (token.Actived)
                            {
                                continue;
                            }
                            LogHelper.DebugWriteLog("!Actived:" + token.SessionId);
                            if ((int)(DateTime.Now - token.LastActiveTime).TotalSeconds > 5)      //如果用户进程5秒内未重新激活
                            {
                                bool completed = this.CreateProcessAsUser((uint)token.SessionId); //可能用户进程已结束,重新启动用户进程
                                LogHelper.DebugWriteLog("Restart ProcessAsUser:"******"Restart ProcessAsUser activeSessionId:" + activeSessionId + " status:" + isOk);
                                    }
                                    continue;
                                }
                                token.LastActiveTime = DateTime.Now;//延迟最后时间,给用户进程足够时间激活
                            }
                        }
                    Thread.Sleep(1000);
                }
            }, true);
        }
        private void SessionProviderService_Load(object sender, EventArgs e)
        {
            this.Text = "SiMay中间会话服务-IOASJHD BEAT " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

            IntPtr sysMenuHandle = GetSystemMenu(this.Handle, false);

            InsertMenu(sysMenuHandle, 7, MF_SEPARATOR, 0, null);
            InsertMenu(sysMenuHandle, 8, MF_BYPOSITION, IDM_OPTIONS, "系统设置");
            InsertMenu(sysMenuHandle, 9, MF_BYPOSITION, IDM_RUNLOG, "运行日志");

            _log_imgList = new ImageList();
            _log_imgList.Images.Add("ok", Resources.ok);
            _log_imgList.Images.Add("err", Resources.erro);

            logList.SmallImageList = _log_imgList;

            string address = ApplicationConfiguration.IPAddress;
            string port    = ApplicationConfiguration.Port;

            this.lableIPAddress.Text = address;
            this.labelPort.Text      = port;
            this.lableStatrTime.Text = DateTime.Now.ToString();
            var ipe = new IPEndPoint(IPAddress.Parse(address), int.Parse(port));


            var serverConfig = new TcpSocketSaeaServerConfiguration();

            serverConfig.ReuseAddress             = false;
            serverConfig.KeepAlive                = true;
            serverConfig.KeepAliveInterval        = 5000;
            serverConfig.KeepAliveSpanTime        = 1000;
            serverConfig.PendingConnectionBacklog = int.Parse(ApplicationConfiguration.Backlog);

            _server = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Full, serverConfig, (notify, session) =>
            {
                switch (notify)
                {
                case TcpSocketCompletionNotify.OnConnected:
                    _connectionCount++;

                    this.Invoke(new Action(() =>
                    {
                        this.lableConnectionCount.Text = _connectionCount.ToString();
                    }));

                    //创建通道上下文,等待确认通道类型
                    TcpChannelContext context    = new TcpChannelContext(session);
                    context.OnChannelTypeNotify += Context_TcpAwaitnotifyProc;

                    _channelContexts.Add(context);
                    break;

                case TcpSocketCompletionNotify.OnSend:
                    this._uploadTransferBytes += session.SendTransferredBytes;
                    break;

                case TcpSocketCompletionNotify.OnDataReceiveing:
                    this._receiveTransferBytes += session.ReceiveBytesTransferred;

                    ((TcpChannelContext)session.AppTokens[0]).OnMessage(session);
                    break;

                case TcpSocketCompletionNotify.OnClosed:
                    _connectionCount--;

                    this.Invoke(new Action(() =>
                    {
                        this.lableConnectionCount.Text = _connectionCount.ToString();
                    }));

                    this.SessionClosed(session);
                    break;

                default:
                    break;
                }
            });
            try
            {
                _server.Listen(ipe);
                LogShowQueueHelper.WriteLog("SiMay中间会话服务端口" + port + "启动成功!");
            }
            catch
            {
                LogShowQueueHelper.WriteLog("SiMay中间会话服务端口" + port + "启动失败!", "err");
            }

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 100;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();

            System.Timers.Timer flow_timer = new System.Timers.Timer();
            flow_timer.Interval = 1000;
            flow_timer.Elapsed += Flow_timer_Elapsed;
            flow_timer.Start();
        }
        public bool StartService(StartServiceOptions options)
        {
            ApplicationConfiguartion.SetOptions(options);

            var serverConfig = new TcpSocketSaeaServerConfiguration();

            serverConfig.ReuseAddress             = false;
            serverConfig.KeepAlive                = true;
            serverConfig.KeepAliveInterval        = 5000;
            serverConfig.KeepAliveSpanTime        = 1000;
            serverConfig.PendingConnectionBacklog = 0;

            var ipe = new IPEndPoint(IPAddress.Parse(ApplicationConfiguartion.Options.LocalAddress), ApplicationConfiguartion.Options.ServicePort);

            _tcpSaeaServer = TcpSocketsFactory.CreateServerAgent(TcpSocketSaeaSessionType.Full, serverConfig, (notify, session) =>
            {
                if (SynchronizationContext.IsNull())
                {
                    NotifyProc(null);
                }
                else
                {
                    SynchronizationContext.Send(NotifyProc, null);
                }

                void NotifyProc(object @object)
                {
                    switch (notify)
                    {
                    case TcpSessionNotify.OnConnected:

                        ApportionDispatcher apportionDispatcher        = new ApportionDispatcher();
                        apportionDispatcher.ApportionTypeHandlerEvent += ApportionTypeHandlerEvent;
                        apportionDispatcher.LogOutputEventHandler     += ApportionDispatcher_LogOutputEventHandler;
                        apportionDispatcher.SetSession(session);

                        break;

                    case TcpSessionNotify.OnSend:
                        break;

                    case TcpSessionNotify.OnDataReceiveing:
                        this.OnDataReceiveingHandler(session);
                        break;

                    case TcpSessionNotify.OnClosed:
                        this.OnClosedHandler(session);
                        break;

                    default:
                        break;
                    }
                }
            });

            try
            {
                _tcpSaeaServer.Listen(ipe);
                LogOutputEventHandler?.Invoke(LogOutLevelType.Debug, $"SiMay中间会话服务器监听 {ipe.Port} 端口启动成功!");
                return(true);
            }
            catch (Exception ex)
            {
                LogOutputEventHandler?.Invoke(LogOutLevelType.Error, $"SiMay中间会话服务器启动发生错误,端口:{ipe.Port} 错误信息:{ex.Message}!");
                return(false);
            }
        }