public TcpSocketSaeaSession(
            TcpSocketSaeaServerConfiguration configuration,
            IBufferManager bufferManager,
            SaeaPool saeaPool,
            ITcpSocketSaeaServerMessageDispatcher dispatcher,
            TcpSocketSaeaServer server)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration");
            if (bufferManager == null)
                throw new ArgumentNullException("bufferManager");
            if (saeaPool == null)
                throw new ArgumentNullException("saeaPool");
            if (dispatcher == null)
                throw new ArgumentNullException("dispatcher");
            if (server == null)
                throw new ArgumentNullException("server");

            _configuration = configuration;
            _bufferManager = bufferManager;
            _saeaPool = saeaPool;
            _dispatcher = dispatcher;
            _server = server;

            _receiveBuffer = _bufferManager.BorrowBuffer();
            _receiveBufferOffset = 0;
        }
Exemple #2
0
 public static TcpSocketSaeaServer CreateServerAgent(
     TcpSocketSaeaSessionType saeaSessionType,
     TcpSocketSaeaServerConfiguration configuration,
     NotifyEventHandler <TcpSocketCompletionNotify, TcpSocketSaeaSession> completetionNotify)
 {
     configuration._intervalWhetherService = true;
     return(new TcpSocketSaeaServer(saeaSessionType, configuration, completetionNotify));
 }
 public TcpSocketSaeaServer(
     IPAddress listenedAddress, int listenedPort,
     Func<TcpSocketSaeaSession, byte[], int, int, Task> onSessionDataReceived = null,
     Func<TcpSocketSaeaSession, Task> onSessionStarted = null,
     Func<TcpSocketSaeaSession, Task> onSessionClosed = null,
     TcpSocketSaeaServerConfiguration configuration = null)
     : this(new IPEndPoint(listenedAddress, listenedPort), onSessionDataReceived, onSessionStarted, onSessionClosed, configuration)
 {
 }
        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;
                }
            });
        }
Exemple #5
0
 internal TcpSocketSaeaServer(
     TcpSocketSaeaSessionType saeaSessionType,
     TcpSocketSaeaServerConfiguration configuration,
     NotifyEventHandler <TcpSocketCompletionNotify, TcpSocketSaeaSession> completetionNotify)
     : base(saeaSessionType, configuration, completetionNotify)
 {
     this._config = configuration;
     if (configuration.AppKeepAlive &&
         saeaSessionType == TcpSocketSaeaSessionType.Packet)
     {
         var keepAliveThread = new Thread(AppKeepAliveWorkThread);
         keepAliveThread.IsBackground = true;
         keepAliveThread.Start();
     }
 }
        public async Task StartAsync(EndPoint endPoint)
        {
            var config = new TcpSocketSaeaServerConfiguration();
            _server = new TcpSocketSaeaServer((IPEndPoint)endPoint, new SimpleMessageDispatcher((session, message) =>
            {
                var sender = new SimpleServerMessageSender(_transportMessageEncoder, session, _logger);
                OnReceived(sender, message);
            }, _transportMessageDecoder, _logger), config);
            _server.Listen();

#if NET45 || NET451
            await Task.FromResult(1);
#else
            await Task.CompletedTask;
#endif
        }
        public TcpSocketSaeaServer(IPEndPoint listenedEndPoint, ITcpSocketSaeaServerMessageDispatcher dispatcher, TcpSocketSaeaServerConfiguration configuration = null)
        {
            if (listenedEndPoint == null)
                throw new ArgumentNullException("listenedEndPoint");
            if (dispatcher == null)
                throw new ArgumentNullException("dispatcher");

            this.ListenedEndPoint = listenedEndPoint;
            _dispatcher = dispatcher;
            _configuration = configuration ?? new TcpSocketSaeaServerConfiguration();

            if (_configuration.FrameBuilder == null)
                throw new InvalidProgramException("The frame handler in configuration cannot be null.");

            Initialize();
        }
        public async Task StartAsync(EndPoint endPoint)
        {
            var config = new TcpSocketSaeaServerConfiguration();

            _server = new TcpSocketSaeaServer((IPEndPoint)endPoint, new SimpleMessageDispatcher((session, message) =>
            {
                var sender = new SimpleServerMessageSender(_transportMessageEncoder, session, _logger);
                OnReceived(sender, message);
            }, _transportMessageDecoder, _logger), config);
            _server.Listen();

#if NET
            await Task.FromResult(1);
#else
            await Task.CompletedTask;
#endif
        }
Exemple #9
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaServerConfiguration();

                _server = new TcpSocketSaeaServer(22222, new SimpleMessageDispatcher(), config);
                _server.Listen();

                Console.WriteLine("TCP server has been started on [{0}].", _server.ListenedEndPoint);
                Console.WriteLine("Type something to send to clients...");
                while (true)
                {
                    try
                    {
                        string text = Console.ReadLine();
                        if (text == "quit")
                        {
                            break;
                        }
                        Task.Run(async() =>
                        {
                            await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                            Console.WriteLine("Server [{0}] broadcasts text -> [{1}].", _server.ListenedEndPoint, text);
                        });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                _server.Shutdown();
                Console.WriteLine("TCP server has been stopped on [{0}].", _server.ListenedEndPoint);
            }
            catch (Exception ex)
            {
                Logger.Get <Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }
Exemple #10
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaServerConfiguration();

                _server = new TcpSocketSaeaServer(22222, new SimpleMessageDispatcher(), config);
                _server.Listen();

                Console.WriteLine("TCP server has been started on [{0}].", _server.ListenedEndPoint);
                Console.WriteLine("Type something to send to clients...");
                while (true)
                {
                    try
                    {
                        string text = Console.ReadLine();
                        if (text == "quit")
                            break;
                        Task.Run(async () =>
                        {
                            await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                            Console.WriteLine("Server [{0}] broadcasts text -> [{1}].", _server.ListenedEndPoint, text);
                        });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                _server.Shutdown();
                Console.WriteLine("TCP server has been stopped on [{0}].", _server.ListenedEndPoint);
            }
            catch (Exception ex)
            {
                Logger.Get<Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }
Exemple #11
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);
        }
Exemple #14
0
 public TcpSocketSaeaServer(int listenedPort, ITcpSocketSaeaServerMessageDispatcher dispatcher, TcpSocketSaeaServerConfiguration configuration = null)
     : this(IPAddress.Any, listenedPort, dispatcher, configuration)
 {
 }
        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);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaServerConfiguration();

                //config.FrameBuilder = new FixedLengthFrameBuilder(20000);
                //config.FrameBuilder = new RawBufferFrameBuilder();
                //config.FrameBuilder = new LineBasedFrameBuilder();
                //config.FrameBuilder = new LengthPrefixedFrameBuilder();
                //config.FrameBuilder = new LengthFieldBasedFrameBuilder();

                _server = new TcpSocketSaeaServer(22222, new SimpleMessageDispatcher(), config);
                _server.Listen();

                Console.WriteLine("TCP server has been started on [{0}].", _server.ListenedEndPoint);
                Console.WriteLine("Type something to send to clients...");
                while (true)
                {
                    try
                    {
                        string text = Console.ReadLine();
                        if (text == "quit")
                        {
                            break;
                        }
                        Task.Run(async() =>
                        {
                            if (text == "many")
                            {
                                text = new string('x', 8192);
                                for (int i = 0; i < 1000000; i++)
                                {
                                    await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                    Console.WriteLine("Server [{0}] broadcasts text -> [{1}].", _server.ListenedEndPoint, text);
                                }
                            }
                            else if (text == "big1k")
                            {
                                text = new string('x', 1024 * 1);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                            else if (text == "big10k")
                            {
                                text = new string('x', 1024 * 10);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                            else if (text == "big100k")
                            {
                                text = new string('x', 1024 * 100);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                            else if (text == "big1m")
                            {
                                text = new string('x', 1024 * 1024 * 1);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                            else if (text == "big10m")
                            {
                                text = new string('x', 1024 * 1024 * 10);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                            else if (text == "big100m")
                            {
                                text = new string('x', 1024 * 1024 * 100);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                            else if (text == "big1g")
                            {
                                text = new string('x', 1024 * 1024 * 1024);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                            else
                            {
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1} Bytes].", _server.ListenedEndPoint, text.Length);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.Get <Program>().Error(ex.Message, ex);
                    }
                }

                _server.Shutdown();
                Console.WriteLine("TCP server has been stopped on [{0}].", _server.ListenedEndPoint);
            }
            catch (Exception ex)
            {
                Logger.Get <Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }
Exemple #17
0
 public TcpSocketSaeaServer(IPAddress listenedAddress, int listenedPort, ITcpSocketSaeaServerMessageDispatcher dispatcher, TcpSocketSaeaServerConfiguration configuration = null)
     : this(new IPEndPoint(listenedAddress, listenedPort), dispatcher, configuration)
 {
 }
        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();
        }
Exemple #19
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaServerConfiguration();

                //config.FrameBuilder = new FixedLengthFrameBuilder(20000);
                //config.FrameBuilder = new RawBufferFrameBuilder();
                //config.FrameBuilder = new LineBasedFrameBuilder();
                //config.FrameBuilder = new LengthPrefixedFrameBuilder();
                //config.FrameBuilder = new LengthFieldBasedFrameBuilder();

                _server = new TcpSocketSaeaServer(22222, new SimpleMessageDispatcher(), config);
                _server.Listen();

                Console.WriteLine("TCP server has been started on [{0}].", _server.ListenedEndPoint);
                Console.WriteLine("Type something to send to clients...");
                while (true)
                {
                    try
                    {
                        string text = Console.ReadLine();
                        if (text == "quit")
                            break;
                        Task.Run(async () =>
                        {
                            if (text == "many")
                            {
                                text = new string('x', 8192);
                                for (int i = 0; i < 1000000; i++)
                                {
                                    await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                    Console.WriteLine("Server [{0}] broadcasts text -> [{1}].", _server.ListenedEndPoint, text);
                                }
                            }
                            else if (text == "big")
                            {
                                text = new string('x', 1024 * 1024 * 100);
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1}].", _server.ListenedEndPoint, text);
                            }
                            else
                            {
                                await _server.BroadcastAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Server [{0}] broadcasts text -> [{1}].", _server.ListenedEndPoint, text);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.Get<Program>().Error(ex.Message, ex);
                    }
                }

                _server.Shutdown();
                Console.WriteLine("TCP server has been stopped on [{0}].", _server.ListenedEndPoint);
            }
            catch (Exception ex)
            {
                Logger.Get<Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }
Exemple #20
0
 public TcpSocketSaeaServer(
     IPEndPoint listenedEndPoint,
     Func<TcpSocketSaeaSession, byte[], int, int, Task> onSessionDataReceived = null,
     Func<TcpSocketSaeaSession, Task> onSessionStarted = null,
     Func<TcpSocketSaeaSession, Task> onSessionClosed = null,
     TcpSocketSaeaServerConfiguration configuration = null)
     : this(listenedEndPoint,
           new InternalTcpSocketSaeaServerMessageDispatcherImplementation(onSessionDataReceived, onSessionStarted, onSessionClosed),
           configuration)
 {
 }
        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);
            }
        }