Ejemplo n.º 1
0
        private async Task <MessageClient> Reconnect(ServerAgentDefinition agent, TimeSpan timeout)
        {
            var client = new MessageClient(PhotonServer.Instance.MessageRegistry)
            {
                //Context = sessionBase,
            };

            //MessageClient.ThreadException += MessageClient_OnThreadException;
            var tokenSource = new CancellationTokenSource(timeout);

            while (!tokenSource.IsCancellationRequested)
            {
                try {
                    await client.ConnectAsync(agent.TcpHost, agent.TcpPort, tokenSource.Token);
                }
                catch (SocketException) {
                    await Task.Delay(1000, tokenSource.Token);

                    continue;
                }

                var versionRequest = new AgentGetVersionRequest();

                var versionResponse = await client.Send(versionRequest)
                                      .GetResponseAsync <AgentGetVersionResponse>(tokenSource.Token);

                if (versionResponse.Version == UpdateVersion)
                {
                    return(client);
                }
            }

            client.Dispose();
            return(null);
        }
Ejemplo n.º 2
0
        private async Task ConnectToAgent(CancellationToken token)
        {
            var agentAddress = $"{Agent.TcpHost}:{Agent.TcpPort}";

            Log.Debug($"Connecting to TCP Agent '{agentAddress}'...");

            try {
                await MessageClient.ConnectAsync(Agent.TcpHost, Agent.TcpPort, Token);

                Log.Info($"Connected to TCP Agent '{agentAddress}'.");

                Log.Debug($"Performing TCP handshake... [{agentAddress}]");

                await ClientHandshake.Verify(MessageClient, token);

                Log.Info($"Handshake successful. [{agentAddress}].");
            }
            catch (Exception error) {
                Log.Error($"Failed to connect to TCP Agent '{agentAddress}'!", error);
                MessageClient.Dispose();
                throw;
            }

            await OnBeginSession(token);

            Tasks.Start();
        }
Ejemplo n.º 3
0
        public async Task SendMessageOneWay_FromHost_1000x()
        {
            TestMessageProcessor.Count = 0;

            using (var listener = new MessageListener(registry)) {
                using (var client = new MessageClient(registry)) {
                    listener.ConnectionReceived += (sender, e) => {
                        for (var i = 0; i < 1000; i++)
                        {
                            e.Host.SendOneWay(new TestRequestOneWayMessage());
                        }

                        e.Host.Stop();
                    };

                    listener.Listen(IPAddress.Loopback, 10934);
                    await client.ConnectAsync("localhost", 10934, CancellationToken.None);

                    await Task.Delay(200);

                    client.Disconnect();
                }

                Assert.That(TestMessageProcessor.Count, Is.EqualTo(1_000));

                listener.Stop();
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// 启动远程服务器功能(1.绘制屏幕2.收集并发送鼠标键盘命令)
 /// </summary>
 /// <param name="userName"></param>
 public void Init(string userName)
 {
     _mClient            = new MessageClient("wenlirdp_" + userName);
     _mClient.OnMessage += _mClient_OnMessage;
     _mClient.OnFile    += _mClient_OnFile;
     _mClient.ConnectAsync();
 }
Ejemplo n.º 5
0
        public async Task BeginAsync()
        {
            try {
                await messageClient.ConnectAsync(definition.TcpHost, definition.TcpPort);

                Log.Info($"Connected to Agent '{definition.Name}'.");
            }
            catch (Exception error) {
                Log.Error($"Failed to connect to Agent '{definition.Name}'!", error);
                throw new ApplicationException($"Failed to connect to Agent '{definition.Name}'! {error.Message}");
            }

            var message = new BuildSessionBeginRequest {
                ServerSessionId = context.ServerSessionId,
                Project         = context.Project,
                AssemblyFile    = context.AssemblyFilename,
                PreBuild        = context.PreBuild,
                GitRefspec      = context.GitRefspec,
                BuildNumber     = context.BuildNumber,
            };

            try {
                var response = await messageClient.Send(message)
                               .GetResponseAsync <BuildSessionBeginResponse>();

                AgentSessionId = response.SessionId;
            }
            catch (Exception error) {
                throw new ApplicationException($"Failed to start Agent Session! {error.Message}");
            }

            BuildTasks.Start();
        }
Ejemplo n.º 6
0
        private static void LinkTest()
        {
            ConsoleHelper.WriteLine("回车开始连接测试...");

            ConsoleHelper.ReadLine();

            var count = 60 * 1000;

            MessageClient mclient;

            Task.Run(() =>
            {
                ConsoleHelper.WriteLine("单机连接测试正在初始化...");

                for (int i = 0; i < count; i++)
                {
                    mclient              = new MessageClient();
                    mclient.OnConnected += Mclient_OnConnected;
                    mclient.ConnectAsync();
                }

                Task.Run(() =>
                {
                    while (_connectCount < count)
                    {
                        Thread.Sleep(1000);
                        ConsoleHelper.WriteLine($"单机连接测试已建立连接:{_connectCount} 未连接:{count - _connectCount}");
                    }
                    ConsoleHelper.WriteLine($"单机{count}连接已完成!");
                });
            });
        }
Ejemplo n.º 7
0
        private async Task AgentAction(ServerAgent agent)
        {
            using (var messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry)) {
                Output.Append("Connecting to agent ", ConsoleColor.DarkCyan)
                .Append(agent.Name, ConsoleColor.Cyan)
                .AppendLine("...", ConsoleColor.DarkCyan);

                try {
                    await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, TokenSource.Token);

                    var handshakeRequest = new HandshakeRequest {
                        Key           = Guid.NewGuid().ToString(),
                        ServerVersion = Configuration.Version,
                    };

                    var timeout           = TimeSpan.FromSeconds(HandshakeTimeoutSec);
                    var handshakeResponse = await messageClient.Handshake <HandshakeResponse>(handshakeRequest, timeout, TokenSource.Token);

                    if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal))
                    {
                        throw new ApplicationException("Handshake Failed! An invalid key was returned.");
                    }

                    if (!handshakeResponse.PasswordMatch)
                    {
                        throw new ApplicationException("Handshake Failed! Unauthorized.");
                    }
                }
                catch (Exception error) {
                    Output.Append("Failed to connect to agent ", ConsoleColor.DarkRed)
                    .Append(agent.Name, ConsoleColor.Red)
                    .AppendLine("!", ConsoleColor.DarkRed)
                    .AppendLine(error.UnfoldMessages(), ConsoleColor.DarkYellow);

                    return;
                }

                Output.AppendLine("Agent connected.", ConsoleColor.DarkGreen);

                Output.Append("Updating Agent ", ConsoleColor.DarkCyan)
                .Append(agent.Name, ConsoleColor.Cyan)
                .AppendLine("...", ConsoleColor.DarkCyan);

                try {
                    await UpdateAgent(agent, messageClient, TokenSource.Token);

                    Output.Append("Agent ", ConsoleColor.DarkGreen)
                    .Append(agent.Name, ConsoleColor.Green)
                    .AppendLine(" updated successfully.", ConsoleColor.DarkGreen);
                }
                catch (Exception error) {
                    Output.Append("Failed to update agent ", ConsoleColor.DarkRed)
                    .Append(agent.Name, ConsoleColor.Red)
                    .AppendLine("!", ConsoleColor.DarkRed)
                    .AppendLine(error.UnfoldMessages(), ConsoleColor.DarkYellow);
                }
            }
        }
Ejemplo n.º 8
0
        private async Task <MessageClient> Reconnect(ServerAgent agent, TimeSpan timeout)
        {
            var client = new MessageClient(PhotonServer.Instance.MessageRegistry);

            client.ThreadException += (o, e) => {
                var error = (Exception)e.ExceptionObject;
                Output.AppendLine("An error occurred while messaging the client!", ConsoleColor.DarkRed)
                .AppendLine(error.UnfoldMessages());

                Log.Error("Message Client error after update!", error);
            };

            var tokenSource = new CancellationTokenSource(timeout);

            var token = tokenSource.Token;

            while (true)
            {
                token.ThrowIfCancellationRequested();

                try {
                    await client.ConnectAsync(agent.TcpHost, agent.TcpPort, tokenSource.Token);

                    var handshakeRequest = new HandshakeRequest {
                        Key           = Guid.NewGuid().ToString(),
                        ServerVersion = Configuration.Version,
                    };

                    var handshakeTimeout  = TimeSpan.FromSeconds(HandshakeTimeoutSec);
                    var handshakeResponse = await client.Handshake <HandshakeResponse>(handshakeRequest, handshakeTimeout, TokenSource.Token);

                    if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal))
                    {
                        throw new ApplicationException("Handshake Failed! An invalid key was returned.");
                    }

                    if (!handshakeResponse.PasswordMatch)
                    {
                        throw new ApplicationException("Handshake Failed! Unauthorized.");
                    }

                    var versionRequest = new AgentGetVersionRequest();

                    var versionResponse = await client.Send(versionRequest)
                                          .GetResponseAsync <AgentGetVersionResponse>(token);

                    if (!VersionTools.HasUpdates(versionResponse.Version, UpdateVersion))
                    {
                        break;
                    }
                }
                catch (SocketException) {
                    await Task.Delay(1000, tokenSource.Token);
                }
            }

            return(client);
        }
Ejemplo n.º 9
0
 public void Start(string userName, string channelID)
 {
     _userName         = userName;
     _channelID        = channelID;
     Client            = new MessageClient(_userName);
     Client.OnLogined += Client_OnLogined;
     Client.OnMessage += Client_OnMessage;
     Client.OnError   += Client_OnError;
     Client.ConnectAsync();
 }
Ejemplo n.º 10
0
 /// <summary>
 /// 开始桌面共享、远程协助(发送图片)
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="isHelp"></param>
 /// <param name="qualityLevel"></param>
 /// <param name="fps"></param>
 public void StartSendCapture(string remote, bool isHelp = true, QualityLevelEnum qualityLevel = QualityLevelEnum.Normal, int fps = 1)
 {
     _isHelp         = isHelp;
     _qualityLevel   = qualityLevel;
     _fps            = fps;
     _isStartCapture = true;
     _mCleint.ConnectAsync();
     _remote = "wenlirdp_" + remote;
     while (!_mCleint.IsConnected)
     {
         Thread.Sleep(10);
     }
     this.SendRequest();
 }
Ejemplo n.º 11
0
        private async Task AgentAction(ServerAgent agent)
        {
            using (var messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry)) {
                Output.WriteBlock(block => block
                                  .Write("Connecting to agent ", ConsoleColor.DarkCyan)
                                  .Write(agent.Name, ConsoleColor.Cyan)
                                  .WriteLine("...", ConsoleColor.DarkCyan));

                try {
                    await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, TokenSource.Token);

                    await ClientHandshake.Verify(messageClient, TokenSource.Token);
                }
                catch (Exception error) {
                    Output.WriteBlock(block => block
                                      .Write("Failed to connect to agent ", ConsoleColor.DarkRed)
                                      .Write(agent.Name, ConsoleColor.Red)
                                      .WriteLine("!", ConsoleColor.DarkRed)
                                      .WriteLine(error.UnfoldMessages(), ConsoleColor.DarkYellow));

                    return;
                }

                Output.WriteLine("Agent connected.", ConsoleColor.DarkGreen);

                Output.WriteBlock(block => block
                                  .Write("Updating Agent ", ConsoleColor.DarkCyan)
                                  .Write(agent.Name, ConsoleColor.Cyan)
                                  .WriteLine("...", ConsoleColor.DarkCyan));

                try {
                    await UpdateAgent(agent, messageClient, TokenSource.Token);

                    Output.WriteBlock(block => block
                                      .Write("Agent ", ConsoleColor.DarkGreen)
                                      .Write(agent.Name, ConsoleColor.Green)
                                      .WriteLine(" updated successfully.", ConsoleColor.DarkGreen));
                }
                catch (Exception error) {
                    Output.WriteBlock(block => block
                                      .Write("Failed to update agent ", ConsoleColor.DarkRed)
                                      .Write(agent.Name, ConsoleColor.Red)
                                      .WriteLine("!", ConsoleColor.DarkRed)
                                      .WriteLine(error.UnfoldMessages(), ConsoleColor.DarkYellow));
                }
            }
        }
Ejemplo n.º 12
0
        private async Task <MessageClient> Reconnect(ServerAgent agent, TimeSpan timeout, CancellationToken token)
        {
            using (var timeoutTokenSource = new CancellationTokenSource(timeout))
                using (var mergedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutTokenSource.Token, token)) {
                    while (true)
                    {
                        mergedTokenSource.Token.ThrowIfCancellationRequested();

                        var client = new MessageClient(PhotonServer.Instance.MessageRegistry);

                        try {
                            using (var connectionTimeoutTokenSource = new CancellationTokenSource(20_000))
                                using (var connectTokenSource = CancellationTokenSource.CreateLinkedTokenSource(mergedTokenSource.Token, connectionTimeoutTokenSource.Token)) {
                                    await client.ConnectAsync(agent.TcpHost, agent.TcpPort, connectTokenSource.Token);

                                    await ClientHandshake.Verify(client, connectTokenSource.Token);

                                    var versionRequest = new AgentGetVersionRequest();

                                    var versionResponse = await client.Send(versionRequest)
                                                          .GetResponseAsync <AgentGetVersionResponse>(connectTokenSource.Token);

                                    if (string.IsNullOrEmpty(versionResponse.Version))
                                    {
                                        Log.Warn("An empty version response was received!");
                                        continue;
                                    }

                                    if (!VersionTools.HasUpdates(versionResponse.Version, UpdateVersion))
                                    {
                                        return(client);
                                    }
                                }
                        }
                        catch (SocketException) {}
                        catch (OperationCanceledException) {}
                        catch (Exception error) {
                            Log.Warn("An unhandled exception occurred while attempting to reconnect to an updating agent.", error);
                        }

                        client.Dispose();

                        await Task.Delay(3_000, mergedTokenSource.Token);
                    }
                }
        }
Ejemplo n.º 13
0
        private async Task AgentAction(ServerAgent agent)
        {
            using (var messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry)) {
                try {
                    Output.WriteLine($"[{agent.Name}] Connecting...'", ConsoleColor.White);

                    await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, TokenSource.Token);

                    await ClientHandshake.Verify(messageClient, TokenSource.Token);

                    Output.WriteLine($"[{agent.Name}] Connected.", ConsoleColor.DarkCyan);
                }
                catch (Exception error) {
                    using (var block = Output.WriteBlock()) {
                        block.WriteLine($"[{agent.Name}] Connection Failed!", ConsoleColor.DarkRed);
                        block.WriteLine(error.UnfoldMessages(), ConsoleColor.DarkYellow);
                    }

                    return;
                }

                var userMgr        = PhotonServer.Instance.UserMgr;
                var securityConfig = PhotonServer.Instance.ServerConfiguration.Value.Security;

                var message = new SecurityPublishRequest {
                    Users                 = userMgr.AllUsers.ToArray(),
                    UserGroups            = userMgr.AllGroups.ToArray(),
                    SecurityEnabled       = securityConfig.Enabled,
                    SecurityDomainEnabled = securityConfig.DomainEnabled,
                };

                Output.WriteLine($"[{agent.Name}] Publishing security configuration...", ConsoleColor.White);

                await messageClient.Send(message)
                .GetResponseAsync();

                Output.WriteLine($"[{agent.Name}] security configuration published.", ConsoleColor.DarkGreen);

                try {
                    Output.WriteLine($"[{agent.Name}] Disconnecting...", ConsoleColor.White);

                    messageClient.Disconnect();
                }
                catch {}
            }
        }
Ejemplo n.º 14
0
        private async Task AgentAction(ServerAgentDefinition agent)
        {
            using (var messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry)) {
                await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, CancellationToken.None);

                var agentVersionRequest = new AgentGetVersionRequest();

                var agentVersionResponse = await messageClient.Send(agentVersionRequest)
                                           .GetResponseAsync <AgentGetVersionResponse>();

                if (!HasUpdates(agentVersionResponse.Version, LatestAgentVersion))
                {
                    // TODO: Print Up-To-Date message
                    return;
                }

                await UpdateAgent(agent, messageClient);
            }
        }
Ejemplo n.º 15
0
        private static async Task <string> GetAgentVersion(ServerAgent agent, CancellationToken token)
        {
            MessageClient messageClient = null;

            try {
                messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry);
                await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, token);

                var handshakeRequest = new HandshakeRequest {
                    Key           = Guid.NewGuid().ToString(),
                    ServerVersion = Configuration.Version,
                };

                var timeout           = TimeSpan.FromSeconds(30);
                var handshakeResponse = await messageClient.Handshake <HandshakeResponse>(handshakeRequest, timeout, token);

                if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal))
                {
                    throw new ApplicationException("Handshake Failed! An invalid key was returned.");
                }

                if (!handshakeResponse.PasswordMatch)
                {
                    throw new ApplicationException("Handshake Failed! Unauthorized.");
                }

                var agentVersionRequest = new AgentGetVersionRequest();

                var agentVersionResponse = await messageClient.Send(agentVersionRequest)
                                           .GetResponseAsync <AgentGetVersionResponse>(token);

                return(agentVersionResponse.Version);
            }
            catch (Exception error) {
                throw new ApplicationException($"Failed to retrieve version of agent '{agent.Name}'!", error);
            }
            finally {
                messageClient?.Dispose();
            }
        }
Ejemplo n.º 16
0
        public async Task SendMessageOneWay_ToHost_1000x()
        {
            TestMessageProcessor.Count = 0;

            using (var listener = new MessageListener(registry)) {
                using (var client = new MessageClient(registry)) {
                    listener.Listen(IPAddress.Any, 10934);
                    await client.ConnectAsync("localhost", 10934, CancellationToken.None);

                    for (var i = 0; i < 1000; i++)
                    {
                        client.SendOneWay(new TestRequestOneWayMessage());
                    }

                    client.Disconnect();
                }

                Assert.That(TestMessageProcessor.Count, Is.EqualTo(1_000));

                listener.Stop();
            }
        }
Ejemplo n.º 17
0
        private async Task <object> ConnectToAgent()
        {
            Log.Debug($"Connecting to TCP Agent '{agent.TcpHost}:{agent.TcpPort}'...");

            try {
                await MessageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, Token);

                Log.Info($"Connected to TCP Agent '{agent.TcpHost}:{agent.TcpPort}'.");

                var handshakeRequest = new HandshakeRequest {
                    Key           = Guid.NewGuid().ToString(),
                    ServerVersion = Configuration.Version,
                };

                var timeout           = TimeSpan.FromSeconds(HandshakeTimeoutSec);
                var handshakeResponse = await MessageClient.Handshake <HandshakeResponse>(handshakeRequest, timeout, Token);

                if (!string.Equals(handshakeRequest.Key, handshakeResponse.Key, StringComparison.Ordinal))
                {
                    throw new ApplicationException("Handshake Failed! An invalid key was returned.");
                }

                if (!handshakeResponse.PasswordMatch)
                {
                    throw new ApplicationException("Handshake Failed! Unauthorized.");
                }
            }
            catch (Exception error) {
                Log.Error($"Failed to connect to TCP Agent '{agent.TcpHost}:{agent.TcpPort}'!", error);
                MessageClient.Dispose();
                throw;
            }

            await OnBeginSession();

            Tasks.Start();
            return(null);
        }
Ejemplo n.º 18
0
        public async Task ClientDisconnectWaitsForMessages()
        {
            var registry = new MessageProcessorRegistry();

            registry.Register(typeof(DelayedTestProcessor));

            using (var listener = new MessageListener(registry))
                using (var client = new MessageClient(registry)) {
                    listener.Listen(IPAddress.Loopback, Port);
                    await client.ConnectAsync(Host, Port, CancellationToken.None);

                    DelayedTestProcessor.Complete = false;
                    var message = new DelayedTestRequest();
                    var _       = client.Send(message).GetResponseAsync <DelayedTestResponse>();

                    client.Disconnect();
                    //await task;

                    Assert.That(DelayedTestProcessor.Complete, Is.True);

                    listener.Stop();
                }
        }
Ejemplo n.º 19
0
        public async Task BeginAsync()
        {
            try {
                await messageClient.ConnectAsync(definition.TcpHost, definition.TcpPort);

                context.Output
                .Append("Connected to Agent ", ConsoleColor.DarkGreen)
                .AppendLine(definition.Name, ConsoleColor.Green);
            }
            catch (Exception error) {
                context.Output
                .Append("Failed to connect to Agent ", ConsoleColor.DarkYellow)
                .Append(definition.Name, ConsoleColor.Yellow)
                .AppendLine($"! {error.Message}", ConsoleColor.DarkYellow);

                throw new ApplicationException($"Failed to connect to Agent '{definition.Name}'! {error.Message}");
            }

            var message = new DeploySessionBeginRequest {
                ServerSessionId       = context.ServerSessionId,
                ProjectPackageId      = context.ProjectPackageId,
                ProjectPackageVersion = context.ProjectPackageVersion,
            };

            try {
                var response = await messageClient.Send(message)
                               .GetResponseAsync <DeploySessionBeginResponse>();

                AgentSessionId = response.AgentSessionId;
            }
            catch (Exception error) {
                throw new ApplicationException($"Failed to start Agent Session! {error.Message}");
            }

            //if (string.IsNullOrEmpty(AgentSessionId))
            //    throw new ApplicationException("Failed to begin agent session!");
        }
Ejemplo n.º 20
0
        private static async Task <string> GetAgentVersion(ServerAgent agent, CancellationToken token)
        {
            MessageClient messageClient = null;

            try {
                messageClient = new MessageClient(PhotonServer.Instance.MessageRegistry);
                await messageClient.ConnectAsync(agent.TcpHost, agent.TcpPort, token);

                await ClientHandshake.Verify(messageClient, token);

                var agentVersionRequest = new AgentGetVersionRequest();

                var agentVersionResponse = await messageClient.Send(agentVersionRequest)
                                           .GetResponseAsync <AgentGetVersionResponse>(token);

                return(agentVersionResponse.Version);
            }
            catch (Exception error) {
                throw new ApplicationException($"Failed to retrieve version of agent '{agent.Name}'!", error);
            }
            finally {
                messageClient?.Dispose();
            }
        }
Ejemplo n.º 21
0
        private static void Main(string[] args)
        {
            Thread serverThread = null;

            Console.WriteLine("是否启动服务器?Y/N");

            var result = Console.ReadLine().ToUpper();

            if (result != "N")
            {
                serverThread = new Thread(() =>
                {
                    ConsoleHelper.WriteLine("正在初始化服务器...", ConsoleColor.Green);
                    server             = new MessageServer();
                    server.OnAccepted += Server_OnAccepted;
                    server.OnErrored  += Server_OnErrored;
                    //server.OnReceived += Server_OnReceived;
                    server.OnUnAccepted += Server_OnUnAccepted;
                    ConsoleHelper.WriteLine("服务器初始化完毕...", ConsoleColor.Green);
                    ConsoleHelper.WriteLine("正在启动服务器...", ConsoleColor.Green);
                    server.Start();

                    ConsoleHelper.WriteLine("正在启动wsserver...");
                    WSServer wsserver = new WSServer();
                    var wsurl         = "ws://172.31.56.106:" + ServerConfig.Instance().WSPort;
                    wsserver.Start(wsurl);
                    ConsoleHelper.WriteLine("wsserver正在运行...");

                    ConsoleHelper.WriteLine("服务器启动完毕...", ConsoleColor.Green);
                });
                serverThread.Start();
                Console.Title = "GFFServer";
                Console.ReadLine();
                //return;
            }

            Console.Title = "GFFClient";

            ConsoleHelper.WriteLine("私信测试开始...");
            var client1 = new MessageClient(uid1);

            client1.OnMessage += Client_OnMessage;
            client1.OnLogined += Client1_OnLogined;
            client1.OnError   += Client_OnError;
            client1.ConnectAsync();

            Console.ReadLine();

            var client2 = new MessageClient(uid2);

            client2.OnMessage += Client_OnMessage;
            client2.OnError   += Client_OnError;
            client2.OnLogined += Client2_OnLogined;
            client2.ConnectAsync();
            Console.ReadLine();


            var channelID = "all";

            ConsoleHelper.WriteLine("频道信息测试开始...");

            var client3 = new MessageClient();

            client3.OnMessage += Client_OnMessage;
            client3.OnError   += Client_OnError;
            client3.OnLogined += Client3_OnLogined;
            client3.ConnectAsync();
            Console.ReadLine();


            ConsoleHelper.WriteLine("订阅端测试开始...");
            Parallel.For(0, 10000, (i) =>
            {
                var ss        = new MessageClient();
                ss.OnLogined += Ss_OnLogined;
                ss.ConnectAsync();
            });
            Console.ReadLine();
            ConsoleHelper.WriteLine("点击回车结束测试...");
            //
            Console.ReadLine();
            if (serverThread != null)
            {
                serverThread.Abort();
            }
        }
Ejemplo n.º 22
0
        private static void FunTest()
        {
            //===============================================================
            ConsoleHelper.WriteLine("回车开始私信测试开始...");
            ConsoleHelper.ReadLine();
            var cc1 = new MessageClient();

            cc1.OnPrivateMessage += Client_OnPrivateMessage;

            var cc2 = new MessageClient();

            cc2.OnPrivateMessage += Client_OnPrivateMessage;

            cc1.Connect();
            cc2.Connect();

            cc1.Login();
            cc2.Login();

            Task.Run(() =>
            {
                while (true)
                {
                    cc1.SendPrivateMsg(cc2.UserToken.ID, "你好呀,cc2!");
                    Thread.Sleep(500);
                }
            });

            Task.Run(() =>
            {
                while (true)
                {
                    cc2.SendPrivateMsg(cc1.UserToken.ID, "你好呀,cc1!");
                    Thread.Sleep(500);
                }
            });

            //===============================================================
            ConsoleHelper.WriteLine("回车开始频道测试开始...");
            ConsoleHelper.ReadLine();

            MessageClient client = new MessageClient();

            client.OnChannelMessage += Client_OnChannelMessage;

            ConsoleHelper.WriteLine("客户正在连接...");

            string channelName = "频道测试一";

            client.Connect();

            ConsoleHelper.WriteLine("客户端就绪");


            client.Login();
            ConsoleHelper.WriteLine("客户端登录成功");

            client.Subscribe(channelName);
            ConsoleHelper.WriteLine("客户端订阅成功");

            Task.Run(() =>
            {
                while (true)
                {
                    client.SendChannelMsg(channelName, "hello!");

                    Thread.Sleep(500);
                }
            });

            //===============================================================
            ConsoleHelper.WriteLine("回车开始订阅频道消息...");
            ConsoleHelper.ReadLine();

            List <MessageClient> list = new List <MessageClient>();

            Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    var c = new MessageClient();
                    if (i < 10)
                    {
                        c.OnChannelMessage += Client_OnChannelMessage2;
                    }
                    c.ConnectAsync((state) =>
                    {
                        c.Login();
                        c.Subscribe(channelName);
                        list.Add(c);
                    });
                }
            });
            //===============================================================

            ConsoleHelper.WriteLine("回车开始群组测试");
            ConsoleHelper.ReadLine();

            cc1.OnGroupMessage += Client_OnGroupMessage;
            cc2.OnGroupMessage += Client_OnGroupMessage;

            var groupName = "萌一号蠢";

            cc1.SendCreateGroup(groupName);
            cc2.SendAddMember(groupName);


            Task.Run(() =>
            {
                while (true)
                {
                    cc1.SendGroupMessage(groupName, "群主广播了!");
                    cc2.SendGroupMessage(groupName, "群主万岁!");
                    Thread.Sleep(100);
                }
            });


            ConsoleHelper.WriteLine("The function test has been completed.");
            ConsoleHelper.ReadLine();
            //===============================================================

            cc2.SendRemoveMember(groupName);
            cc1.SendRemoveGroup(groupName);
            client.Unsubscribe(channelName);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            ConsoleHelper.WriteLine("Message Test");

            ConsoleHelper.WriteLine("服务器正在启动...");

            MessageServer server = new MessageServer();

            server.Start();

            Task.Run(() =>
            {
                while (true)
                {
                    ConsoleHelper.Title = "MessageServer ClientCounts: " + server.ClientCounts;

                    Thread.Sleep(1000);
                }
            });

            ConsoleHelper.WriteLine("服务器就绪");

            //===============================================================

            MessageClient client = new MessageClient();

            client.OnChannelMessage += Client_OnChannelMessage;
            client.OnPrivateMessage += Client_OnPrivateMessage;

            ConsoleHelper.WriteLine("客户正在连接...");

            string channelName = "频道测试一";

            client.ConnectAsync((state) =>
            {
                ConsoleHelper.WriteLine("客户就绪");

                if (state == System.Net.Sockets.SocketError.Success)
                {
                    client.Login();
                    ConsoleHelper.WriteLine("客户登录成功");

                    client.Subscribe(channelName);
                    ConsoleHelper.WriteLine("客户订阅成功");

                    Task.Run(() =>
                    {
                        while (true)
                        {
                            client.SendChannelMsg(channelName, "hello!");

                            Thread.Sleep(60 * 1000);
                        }
                    });


                    ConsoleHelper.WriteLine("客户发送频道消息成功");
                }
            });


            //===============================================================



            ConsoleHelper.ReadLine();
            Console.WriteLine("单机连接测试...");
            List <MessageClient> slist = new List <MessageClient>();

            Task.Run(() =>
            {
                for (int i = 0; i < 50000; i++)
                {
                    var c = new MessageClient();
                    c.ConnectAsync((state) =>
                    {
                        slist.Add(c);
                    });
                    Thread.Sleep(1);
                    if (i > 1000)
                    {
                        Thread.Sleep(10);
                    }
                    if (i > 5000)
                    {
                        Thread.Sleep(100);
                    }
                    if (i > 10000)
                    {
                        Thread.Sleep(1000);
                    }
                }
                Console.WriteLine("单机5W连接就绪...");
            });



            //===============================================================



            ConsoleHelper.ReadLine();
            Console.WriteLine("开始订阅测试...");
            List <MessageClient> list = new List <MessageClient>();

            for (int i = 0; i < 100; i++)
            {
                var c = new MessageClient();
                if (i < 10)
                {
                    c.OnChannelMessage += Client_OnChannelMessage2;
                }
                c.ConnectAsync((state) =>
                {
                    c.Login();
                    c.Subscribe(channelName);
                    list.Add(c);
                });
                Thread.Sleep(10);
            }



            //===============================================================



            ConsoleHelper.ReadLine();
            Console.WriteLine("私信测试");

            var cc1 = new MessageClient();

            cc1.OnPrivateMessage += Client_OnPrivateMessage;

            var cc2 = new MessageClient();

            cc2.OnPrivateMessage += Client_OnPrivateMessage;

            cc1.ConnectAsync((state) =>
            {
                cc1.Login();

                Task.Run(() =>
                {
                    while (true)
                    {
                        if (cc2.Connected)
                        {
                            cc1.SendPrivateMsg(cc2.UserToken.ID, "你好呀,cc2!");
                        }
                        Thread.Sleep(1000);
                    }
                });

                cc1.Subscribe(channelName);

                list.Add(cc1);
            });


            cc2.ConnectAsync((state) =>
            {
                cc2.Login();

                Task.Run(() =>
                {
                    while (true)
                    {
                        if (cc1.Connected)
                        {
                            cc2.SendPrivateMsg(cc1.UserToken.ID, "你好呀,cc1!");
                        }
                        Thread.Sleep(1000);
                    }
                });

                cc2.Subscribe(channelName);

                list.Add(cc2);
            });



            //===============================================================



            ConsoleHelper.ReadLine();
            Console.WriteLine("群组测试");

            cc1.OnGroupMessage += Client_OnGroupMessage;
            cc2.OnGroupMessage += Client_OnGroupMessage;

            var groupName = "萌一号蠢";

            cc1.SendCreateGroup(groupName);
            cc2.SendAddMember(groupName);


            Task.Run(() =>
            {
                while (true)
                {
                    cc1.SendGroupMessage(groupName, "群主广播了!");
                    cc2.SendGroupMessage(groupName, "群主万岁!");
                    Thread.Sleep(100);
                }
            });



            //===============================================================



            ConsoleHelper.ReadLine();

            cc2.SendRemoveMember(groupName);
            cc1.SendRemoveGroup(groupName);
            client.Unsubscribe(channelName);


            Console.WriteLine("测试完成");
            ConsoleHelper.ReadLine();
        }