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;
                }
            });
        }
Exemplo n.º 2
0
        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
        }
Exemplo n.º 3
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();
        }
Exemplo n.º 4
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();
        }
Exemplo n.º 5
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;
                }
            });
        }
Exemplo n.º 7
0
        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);
        }
Exemplo n.º 8
0
        public async Task StartAsync(EndPoint endPoint)
        {
            _server = new TcpSocketSaeaServer((IPEndPoint)endPoint, async(session, data, offset, count) =>
            {
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("接收到数据包。");
                }
                var message = _transportMessageDecoder.Decode(data.Skip(offset).Take(count).ToArray());
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("接收到消息:" + message.Id);
                }
                var sender = new SimpleServerMessageSender(_transportMessageEncoder, session, _logger);
                await OnReceived(sender, message);
            });
            _server.Listen();

#if NET
            await Task.FromResult(1);
#else
            await Task.CompletedTask;
#endif
        }
Exemplo n.º 9
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();
        }
Exemplo n.º 10
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();
        }
        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);
            }
        }