Example #1
0
        static void Main(string[] args)
        {
            Dictionary <string, OnlineScript> DicOnlineScripts = new Dictionary <string, OnlineScript>();

            IniFile ConnectionInfo       = IniFile.ReadFromFile("Connection Info.ini");
            string  ConnectionChain      = ConnectionInfo.ReadField("Communication Server Info", "Connection Chain");
            string  UserInformationChain = ConnectionInfo.ReadField("User Information Info", "Connection Chain");

            CommunicationMongoDBManager Databse = new CommunicationMongoDBManager();

            Databse.Init(ConnectionChain, UserInformationChain, "BattleMap");
            //Databse.Init(ConnectionChain, UserInformationChain, "TripleThunder");
            CommunicationServer OnlineServer = new CommunicationServer(Databse, DicOnlineScripts);

            DicOnlineScripts.Add(SendGlobalMessageScriptServer.ScriptName, new SendGlobalMessageScriptServer(OnlineServer));
            DicOnlineScripts.Add(IdentifyScriptClient.ScriptName, new IdentifyScriptServer(OnlineServer));
            DicOnlineScripts.Add(AskForPlayersScriptServer.ScriptName, new AskForPlayersScriptServer(OnlineServer));
            DicOnlineScripts.Add(CreateOrJoinCommunicationGroupScriptServer.ScriptName, new CreateOrJoinCommunicationGroupScriptServer(OnlineServer));
            DicOnlineScripts.Add(JoinCommunicationGroupScriptServer.ScriptName, new JoinCommunicationGroupScriptServer(OnlineServer));
            DicOnlineScripts.Add(LeaveCommunicationGroupScriptServer.ScriptName, new LeaveCommunicationGroupScriptServer(OnlineServer));
            DicOnlineScripts.Add(AskClientInfoScriptServer.ScriptName, new AskClientInfoScriptServer(OnlineServer));
            DicOnlineScripts.Add(AddFriendScriptServer.ScriptName, new AddFriendScriptServer(OnlineServer));
            DicOnlineScripts.Add(SendGroupMessageScriptServer.ScriptName, new SendGroupMessageScriptServer(OnlineServer));
            DicOnlineScripts.Add(SendGroupInviteScriptServer.ScriptName, new SendGroupInviteScriptServer(OnlineServer));

            string PublicIP   = ConnectionInfo.ReadField("Communication Server Info", "Public IP");
            int    PublicPort = int.Parse(ConnectionInfo.ReadField("Communication Server Info", "Public Port"));

            Trace.Listeners.Add(new TextWriterTraceListener("Communication Server Error.log", "myListener"));

            OnlineServer.StartListening(PublicIP, PublicPort);
            Console.ReadKey();
            OnlineServer.StopListening();
        }
        public static void HandleMessage(RegisterGame request, CommunicationServer server, Socket handler)
        {
            if (request == null)
            {
                return;
            }

            Game.Game g;

            lock (joinLock)
            {
                g = new Game.Game(gameId: server.RegisteredGames.NextGameId(), name: request.NewGameInfo.gameName,
                                  bluePlayers: request.NewGameInfo.blueTeamPlayers,
                                  redPlayers: request.NewGameInfo.redTeamPlayers, gameMaster: handler
                                  );
                try
                {
                    server.RegisteredGames.RegisterGame(g);
                }
                catch
                {
                    return;
                }
            }

            ConfirmGameRegistration gameRegistration = new ConfirmGameRegistration()
            {
                gameId = (ulong)g.Id
            };

            var response = XmlMessageConverter.ToXml(gameRegistration);

            server.ConnectionEndpoint.SendFromServer(handler, response);
        }
Example #3
0
 public MainWindow()
 {
     InitializeComponent();
     server = new CommunicationServer(11002);
     server.OnRegistringEvent += new CommunicationServer.OnRegistring(server_OnRegistringEvent);
     RegistrationService.Subscribed += new EventHandler<RegistrationService.SubscriptionEventArgs>(RegistrationService_Subscribed);
 }
 public void CanConnect()
 {
     using (var server = new CommunicationServer("testConnect"))
     {
         var count = 0;
         var lck   = new object();
         server.Listen();
         server.RaiseNewClientEvent += (x, e) => {
             lock (lck)
             {
                 count++;
                 Monitor.Pulse(lck);
             }
         };
         using (var client = CommunicationChannel.Client(server.PipeName))
         {
             Assert.True(client.IsConnected);
             Assert.True(WaitFor(lck, () => count == 1, 1000));
         }
         using (var client = CommunicationChannel.Client(server.PipeName))
         {
             Assert.True(client.IsConnected);
             Assert.True(WaitFor(lck, () => count == 2, 1000));
         }
     }
 }
        public void ProtobufSerialization()
        {
            var fmt1 = new OELibProtobufFormatter.OELibProtobufFormatter();

            var go     = new AutoResetEvent(false);
            var server =
                new CommunicationServer <ServerSideConnection>(new IPEndPoint(IPAddress.Any, 1027))
            {
                Formatter = fmt1
            };

            server.Start();
            server.ClientConnected += (s, e) => go.Set();
            var client = new ClientSideConnection(fmt1);

            client.Start("127.0.0.1", 1027);
            var ok = go.WaitOne(500);

            Assert.IsTrue(ok);
            var go2 = new AutoResetEvent(false);

            client.MessageReceived += (s, e) =>
            {
                if (e is Echo3)
                {
                    go2.Set();
                }
            };

            server.Connections.First().SendMessage(new Echo3());
            var ok2 = go2.WaitOne(500);

            Assert.IsTrue(ok2);
        }
Example #6
0
 public void SetupServer()
 {
     if (serverForVcs == null)
     {
         serverForVcs = new CommunicationServer(_vcsPort);
     }
 }
 public void CanConnect()
 {
     using (var server = new CommunicationServer("testConnect"))
     {
         var count = 0;
         var lck   = new object();
         server.Listen();
         server.RaiseNewClientEvent += (x, e) =>
         {
             lock (lck)
             {
                 count++;
                 Monitor.Pulse(lck);
             }
         };
         using (var client = CommunicationChannel.Client(server.PipeName))
         {
             client.IsConnected.ShouldBeTrue("First client could not connect to server pipe");
             WaitFor(lck, () => count == 1, 1000).ShouldBeTrue("First client connection event was not raised");
         }
         using (var client = CommunicationChannel.Client(server.PipeName))
         {
             client.IsConnected.ShouldBeTrue("Second client could not connect to server pipe");
             WaitFor(lck, () => count == 2, 1000).ShouldBeTrue("First client connection event was not raised");
         }
     }
 }
        public void ToAgentFromGM()
        {
            using (CommunicationServer communicationServer = new CommunicationServer(config))
            {
                //connecting game master
                communicationServer.StartConnectingGameMaster();
                TcpClient gameMasterSide = new TcpClient();
                gameMasterSide.Connect(IPAddress.Loopback, communicationServer.PortCSforGM);
                communicationServer.AcceptGameMaster();
                IMessageSenderReceiver senderReceiverGameMaster = new StreamMessageSenderReceiver(gameMasterSide.GetStream(), new Parser());

                //connecting agent
                var AgentConnectTask = new Task(() => communicationServer.ConnectAgents());
                AgentConnectTask.Start();
                while (communicationServer.PortCSforAgents == 0)
                {
                    Thread.Sleep(50);
                }
                TcpClient agentSide = new TcpClient("localhost", communicationServer.PortCSforAgents);
                IMessageSenderReceiver senderReceiverAgent = new StreamMessageSenderReceiver(agentSide.GetStream(), new Parser());


                //ensuring agent is registered in communication server
                senderReceiverAgent.Send(new Message <JoinGameRequest>(new JoinGameRequest {
                    TeamId = "red"
                }));
                gameMasterSide.GetStream().Read(new byte[1], 0, 1);

                //sending message to agent
                var sentMessage = new Message <GameStarted>()
                {
                    AgentId        = 1,
                    MessagePayload = new GameStarted()
                };
                senderReceiverGameMaster.Send(sentMessage);


                //waiting for message in agent
                var       expectedMessageId = MessageType.GameStarted;
                Message   receivedMessage   = null;
                Semaphore semaphore         = new Semaphore(0, 100);

                senderReceiverAgent.StartReceiving(m =>
                {
                    semaphore.Release();
                    receivedMessage = m;
                }, (e) => {});
                semaphore.WaitOne();

                Assert.IsFalse(receivedMessage == null);
                Assert.AreEqual(receivedMessage.MessageId, expectedMessageId);

                //after
                gameMasterSide.Close();
                agentSide.Close();
                senderReceiverGameMaster.Dispose();
                senderReceiverAgent.Dispose();
            }
        }
        public static void HandleMessage(GameStarted request, CommunicationServer server, Socket handler)
        {
            //FIXME HELLO BUG HERE BECAUSE WE USE INT in GetGameByID and not ULONG
            IGame game = server.RegisteredGames.GetGameById((int)request.gameId);

            game.HasStarted = true;
            //server.startedGames.Add(game.Name);
        }
Example #10
0
        static void Main(string[] args)
        {
            EventLogger.AddAppender(new Log4NetAppender());
            var ipAddress = "127.0.0.1";
            var port      = 8123;
            var server    = new CommunicationServer(ipAddress, port);

            server.Start();
        }
        public static void HandleMessage(ConfirmJoiningGame request, CommunicationServer server, Socket handler)
        {
            HandleMessage(request as PlayerMessage, server, handler);

            Game.IGame g = server.RegisteredGames.GetGameById((int)request.gameId);
            g.Players.Add(new Game.Player {
                Id = request.playerId
            });
        }
Example #12
0
        static void Main(string[] args)
        {
            ServerCommandLineOptions options = CommandLineParser.ParseArgs <ServerCommandLineOptions>(args, new ServerCommandLineOptions());

            CommunicationServerSettings settings = Configuration.FromFile <CommunicationServerSettings>(options.Conf);
            IConnectionEndpoint         endpoint = new ConnectionEndpoint(options.Port);

            CommunicationServer server = new CommunicationServer(endpoint, settings);

            server.Start();
        }
        public static void HandleMessage(GameMessage request, CommunicationServer server, Socket handler)
        {
            if (request == null)
            {
                return;
            }

            var response = XmlMessageConverter.ToXml(request);

            server.ConnectionEndpoint.SendFromServer(server.RegisteredGames.GetGameById((int)request.gameId).GameMaster, response);
        }
        public static void HandleMessage(PlayerMessage request, CommunicationServer server, Socket handler)
        {
            if (request == null)
            {
                return;
            }

            var response = XmlMessageConverter.ToXml(request);

            server.ConnectionEndpoint.SendFromServer(server.Clients[request.playerId], response);
        }
Example #15
0
        public DotnetTestRunner(string path, IProcessExecutor processProxy, OptimizationFlags flags, IEnumerable <string> testBinariesPaths)
        {
            _logger            = ApplicationLogging.LoggerFactory.CreateLogger <DotnetTestRunner>();
            _flags             = flags;
            _projectFile       = FilePathUtils.NormalizePathSeparators(path);
            _processExecutor   = processProxy;
            _testBinariesPaths = testBinariesPaths;

            _server = new CommunicationServer("CoverageCollector");
            _server.SetLogger((msg) => _logger.LogDebug(msg));
            _server.RaiseNewClientEvent += ConnectionEstablished;
            _server.Listen();
        }
Example #16
0
        /// <summary>
        /// Starts the server.
        /// </summary>
        /// <param name="srcDeviceId">The source device identifier.</param>
        /// <param name="communicationService">The communication service.</param>
        private void StartServer(string srcDeviceId, IServer <Command, FetchRequest, GrpcResponse> communicationService)
        {
            // Grpc server
            CommunicationServer server = new CommunicationServer(communicationService, srcDeviceId);

            // Grpc server actions
            server.OnAction             = async(cmd, streamId, token, header) => { return(await ActionWorker.ProcessCommand(srcDeviceId, cmd, streamId, token, header)); };
            server.OnStreaming          = async(cmd, stream, token, header) => { return(await ActionWorker.ProcessCommand(srcDeviceId, cmd, stream.Id, token, header)); };
            server.OnStreamOpened       = async(stream, token, header) => { return(await ActionWorker.StreamConnected(stream, token, header)); };
            server.OnClientDisconnected = async(id) => { await ActionWorker.StreamDisconnected(id); };
            server.OnLog += (sender, srcid, msg, level) =>
            {
                CommonBaseHandler.Log(sender.ToString(), msg, level);
            };
            server.Start();
        }
Example #17
0
        //加载用户数据
        void ExecuteLoadDataCommand()
        {
            if (modelServer == null) //防止重复初始化
            {
                modelServer                 = PlatformModelServer.GetServer();
                serialPortParameter         = modelServer.CommServer.SerialPortParameter;
                commServer                  = modelServer.CommServer;
                commServer.PropertyChanged += ServerInformation_PropertyChanged;
                SelectedIndexDataBit        = 3;

                RaisePropertyChanged("Baud");
                RaisePropertyChanged("DataBit");
                RaisePropertyChanged("ParityBit");
                RaisePropertyChanged("StopBit");
                RaisePropertyChanged("CommonPort");
            }
        }
        public void CallMethodResponseSerialization()
        {
            var fmt1 = new OELibProtobufFormatter.OELibProtobufFormatter();
            var assemblyQualifiedName = typeof(Echo).AssemblyQualifiedName;

            // ReSharper disable once AssignNullToNotNullAttribute
            fmt1.SerializationHelper.ManualSerilaizationActions.Add(assemblyQualifiedName,
                                                                    new Tuple <Action <System.IO.Stream, object>, Func <System.IO.Stream, string, object> >(
                                                                        (s, o) => {  }, (s, g) => new Echo()));
            var go     = new AutoResetEvent(false);
            var server =
                new CommunicationServer <ServerSideConnection>(new IPEndPoint(IPAddress.Any, 1030))
            {
                Formatter = fmt1
            };

            server.Start();
            server.ClientConnected += (s, e) => go.Set();
            var client = new ClientSideConnection(fmt1);

            client.Start("127.0.0.1", 1030);
            var ok = go.WaitOne(500);

            Assert.IsTrue(ok);
            var go2 = new AutoResetEvent(false);
            CallMethodResponse ee = null;

            client.MessageReceived += (s, e) =>
            {
                ee = e as CallMethodResponse;
                if (ee != null)
                {
                    go2.Set();
                }
            };
            server.Connections.First().SendMessage(
                new CallMethodResponse(new CallMethod("MethodName", new object[] {}, null), new Echo3(), new NullReferenceException())
                );
            var ok2 = go2.WaitOne(500);

            Assert.IsTrue(ok2);
            Assert.IsTrue(ee.Response is Echo3);
            Assert.IsTrue(ee.Exception is NullReferenceException);
        }
Example #19
0
 private void ButtonStartStopServer_Click(object sender, RoutedEventArgs e)
 {
     if (_server == null || !_server.IsRunning)
     {
         _server = new CommunicationServer(
             int.Parse(TextBoxPortNumber.Text.Trim()),
             ShowMessage,
             AddClient,
             RemoveClient,
             UpdatePosition,
             IndicateCurrentMode);
         _server.StartServer();
         ButtonStartStopServer.Content = "Stop Services";
     }
     else
     {
         _server.StopServer();
         ButtonStartStopServer.Content = "Start Services";
     }
 }
        public static void HandleMessage(JoinGame request, CommunicationServer server, Socket handler)
        {
            if (request == null)
            {
                return;
            }

            //if (server.startedGames.Contains(request.gameName))
            //{
            //    ConsoleDebug.Error("Game already started");
            //    return;
            //}


            Game.IGame g = server.RegisteredGames.GetGameByName(request.gameName);
            if (g == null)
            {
                ConsoleDebug.Error("Game with specified name not found");
                return;
            }
            if (g.HasStarted)
            {
                ConsoleDebug.Error("Game already started");
                return;
            }

            lock (joinLock)
            {
                request.playerId          = server.IdForNewClient();
                request.playerIdSpecified = true;
                server.Clients.Add(request.playerId, handler);
                g.Players.Add(new Game.Player {
                    Id = request.playerId
                });
            }

            var response = XmlMessageConverter.ToXml(request);

            server.ConnectionEndpoint.SendFromServer(g.GameMaster, response);
            return;
        }
 public void CanSend()
 {
     using (var server = new CommunicationServer("test"))
     {
         var lck     = new object();
         var message = string.Empty;
         CommunicationChannel serverSide = null;
         server.Listen();
         server.RaiseNewClientEvent += (o, e) =>
         {
             lock (lck)
             {
                 serverSide = e.Client;
                 serverSide.RaiseReceivedMessage += (o2, msg) =>
                 {
                     lock (lck)
                     {
                         message = msg;
                         Monitor.Pulse(lck);
                     }
                 };
                 Monitor.Pulse(lck);
             }
         };
         using (var client = CommunicationChannel.Client(server.PipeName))
         {
             client.IsConnected.ShouldBeTrue("Client could not connect to server pipe");
             WaitFor(lck, () => serverSide != null, 1000).ShouldBeTrue("Client connection event was not raised");
             client.Start();
             client.RaiseReceivedMessage += (o, msg) =>
             {
                 client.SendText(msg);
             };
             serverSide.SendText("it works");
             WaitFor(lck, () => !string.IsNullOrEmpty(message), 1000).ShouldBeTrue("Client message received event was not raised");
             message.ShouldBe("it works");
         }
     }
 }
 public void CanSend()
 {
     using (var server = new CommunicationServer("test"))
     {
         var lck     = new object();
         var message = string.Empty;
         CommunicationChannel serverSide = null;
         server.Listen();
         server.RaiseNewClientEvent += (o, e) =>
         {
             lock (lck)
             {
                 serverSide = e.Client;
                 serverSide.RaiseReceivedMessage += (o2, msg) =>
                 {
                     lock (lck)
                     {
                         message = msg;
                         Monitor.Pulse(lck);
                     }
                 };
                 Monitor.Pulse(lck);
             }
         };
         using (var client = CommunicationChannel.Client(server.PipeName))
         {
             Assert.True(client.IsConnected);
             Assert.True(WaitFor(lck, () => serverSide != null, 1000));
             client.Start();
             client.RaiseReceivedMessage += (o, msg) =>
             {
                 client.SendText(msg);
             };
             serverSide.SendText("it works");
             Assert.True(WaitFor(lck, () => !string.IsNullOrEmpty(message), 1000));
             Assert.Equal("it works", message);
         }
     }
 }
        public void ManualSerialization()
        {
            var fmt1 = new OELibProtobufFormatter.OELibProtobufFormatter();
            var AssemblyQualifiedName = typeof(Echo).AssemblyQualifiedName;

            fmt1.SerializationHelper.ManualSerilaizationActions.Add(AssemblyQualifiedName,
                                                                    new Tuple <Action <System.IO.Stream, object>, Func <System.IO.Stream, string, object> >(
                                                                        (s, o) => {  }, (s, g) => new Echo()));

            var go     = new AutoResetEvent(false);
            var server =
                new CommunicationServer <ServerSideConnection>(new IPEndPoint(IPAddress.Any, 1025))
            {
                Formatter = fmt1
            };

            server.Start();
            server.ClientConnected += (s, e) => go.Set();
            var client = new ClientSideConnection(fmt1);

            client.Start("127.0.0.1", 1025);
            var ok = go.WaitOne(500);

            Assert.IsTrue(ok);
            var go2 = new AutoResetEvent(false);

            client.MessageReceived += (s, e) =>
            {
                if (e is Echo)
                {
                    go2.Set();
                }
            };

            server.Connections.First().SendMessage(new Echo());
            var ok2 = go2.WaitOne(500);

            Assert.IsTrue(ok2);
        }
        public void TestGMConnection()
        {
            //given
            CommunicationServer cs = new CommunicationServer(config);

            //when
            cs.StartConnectingGameMaster();
            Thread thread = new Thread(cs.AcceptGameMaster);

            thread.Start();
            //then
            //doesnt throw exceptions
            Thread.Sleep(100);
            TcpClient     tcpClient     = new TcpClient(cs.IpAddress, cs.PortCSforGM);
            NetworkStream networkStream = tcpClient.GetStream();

            networkStream.Close();

            networkStream.Dispose();
            tcpClient.Dispose();
            networkStream.Dispose();
        }
        public void TestAgentConnection()
        {
            //given
            CommunicationServer cs = new CommunicationServer(config);
            //when
            Thread thread = new Thread(cs.ConnectAgents);

            thread.Start();
            //then
            //doesnt throw exceptions
            Thread.Sleep(100);
            TcpClient     tcpClient     = new TcpClient(cs.IpAddress, cs.PortCSforAgents);
            NetworkStream networkStream = tcpClient.GetStream();
            StreamMessageSenderReceiver streamMessageSenderReceiver = new StreamMessageSenderReceiver(networkStream, new Parser());

            streamMessageSenderReceiver.Send(new Message <JoinGameRequest>(new JoinGameRequest()));
            networkStream.Close();

            networkStream.Dispose();
            tcpClient.Dispose();
            networkStream.Dispose();
        }
        public void Connection()
        {
            var go     = new AutoResetEvent(false);
            var server =
                new CommunicationServer <ServerSideConnection>(new IPEndPoint(IPAddress.Any, 1024))
            {
                Formatter = new OELibProtobufFormatter.OELibProtobufFormatter()
            };

            server.Start();
            server.ClientConnected += (s, e) =>
            {
                go.Set();
            };


            var client = new ClientSideConnection(new OELibProtobufFormatter.OELibProtobufFormatter());

            client.Start("127.0.0.1", 1024);
            var ok = go.WaitOne(500);

            Assert.IsTrue(ok);
            server.Stop();
        }
        public static void HandleMessage(GetGames request, CommunicationServer server, Socket handler)
        {
            List <GameInfo> gi = new List <GameInfo>();

            foreach (var game in server.RegisteredGames)
            {
                if (game.HasStarted)
                {
                    continue;
                }
                gi.Add(new GameInfo()
                {
                    blueTeamPlayers = game.BlueTeamPlayersCount,
                    redTeamPlayers  = game.RedTeamPlayersCount,
                    gameName        = game.Name
                });
            }
            var rg = new RegisteredGames()
            {
                GameInfo = gi.ToArray()
            };

            server.ConnectionEndpoint.SendFromServer(handler, XmlMessageConverter.ToXml(rg));
        }
 public static void HandleMessage(object message, CommunicationServer server, Socket handler)
 {
     ConsoleDebug.Warning("Unknown type");
 }
 public void InitTest()
 {
     gc.RegisterGame(new Game());
     gc.RegisterGame(new Game(name: "g1", gameId: 1, bluePlayers: 2, redPlayers: 2));
     MockServer = new CommunicationServer(new MockEndpoint(), null);
 }
 public CommunicationManager(ILocalConfigManager configManager)
 {
     this._configManager       = configManager;
     this._communicationServer = new CommunicationServer(this._configManager.GetConfig(LocalConfigKeys.CommunicationAddress), this.GetOpenPort(), this.OnApplicationConnection);
 }
Example #31
0
 private void btn_newServer_Click(object sender, EventArgs e)
 {
     Server = new CommunicationServer(Int32.Parse(tx_PortName.Text));
     //Receive Thread
     Task.Run(() => receiveFromClient());
 }