コード例 #1
0
        public void TestSendingGameJoin()
        {
            File.WriteAllText("TMPpath.txt",
                              "{\"CsIP\": \"127.0.0.1\"," +
                              "\"CsPort\": 8080," +
                              "\"teamID\": \"red\"," +
                              "\"strategy\": 1}");
            string[] args = new string[1] {
                "./TMPpath.txt"
            };

            AgentConfiguration configuration = AgentConfiguration.ReadConfiguration(args);

            TcpListener serverSideListener = new TcpListener(IPAddress.Any, configuration.CsPort);

            serverSideListener.Start();
            TcpClient serverSide = null;
            var       task       = new Task(() => serverSide = serverSideListener.AcceptTcpClient());

            task.Start();

            Agent.Agent agent = new Agent.Agent(configuration);
            agent.StartListening();

            task.Wait();
            serverSideListener.Stop();
            IMessageSenderReceiver senderReceiver = new StreamMessageSenderReceiver(serverSide.GetStream(), new Parser());

            senderReceiver.StartReceiving(message =>
            {
                Assert.AreEqual(message.MessageId, MessageType.JoinGameRequest);
            });
        }
コード例 #2
0
        public void TestStreamMessageSenderReceiverCanReceiveMessage()
        {
            //given
            String expected = "Hello world";

            byte[] inputBuffer = new byte[20];

            byte[] textBytes   = Encoding.UTF8.GetBytes(expected);
            byte[] lengthBytes = BitConverter.GetBytes((ushort)textBytes.Length);
            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(lengthBytes);
            }
            Array.Copy(lengthBytes, 0, inputBuffer, 0, 2);
            Array.Copy(textBytes, 0, inputBuffer, 2, textBytes.Length);
            Stream stream = new MemoryStream(inputBuffer);

            StreamMessageSenderReceiver streamMessageSenderReceiver
                = new StreamMessageSenderReceiver(stream, new TestParser());
            BlockingCollection <Message> messages = new BlockingCollection <Message>();

            streamMessageSenderReceiver.StartReceiving(message => messages.Add(message));

            //when
            Message received = messages.Take();

            //then
            Assert.AreEqual(expected, ((Message <JoinGameRequest>)received).MessagePayload.TeamId);
        }
コード例 #3
0
        public void TestCallbackCalledOnDisconnect()
        {
            //given
            (TcpClient clientSide, TcpClient serverSide) = HelperFunctions.TcpConnectClientAndServer();

            Exception receivedException = null;
            StreamMessageSenderReceiver streamMessageSenderReceiver
                = new StreamMessageSenderReceiver(clientSide.GetStream(), new Parser());
            Semaphore semaphore = new Semaphore(0, 100);

            streamMessageSenderReceiver.StartReceiving(message => { }, e =>
                                                       { receivedException = e; semaphore.Release(); });

            //when
            serverSide.Close();
            semaphore.WaitOne();

            //then
            Assert.IsNotNull(receivedException);
            Assert.IsInstanceOfType(receivedException, typeof(CommunicationLibrary.Exceptions.DisconnectedException));

            //after
            streamMessageSenderReceiver.Dispose();
            clientSide.Close();
            semaphore.Dispose();
        }
コード例 #4
0
        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();
            }
        }
コード例 #5
0
        public void TestReceiveRequest()
        {
            StubGuiMaintainer guiMantainer = new StubGuiMaintainer();
            GMConfiguration   config       = new GMConfiguration()
            {
                BoardX                     = 40,
                BoardY                     = 40,
                CsIP                       = "127.0.0.1",
                CsPort                     = 8081,
                MovePenalty                = 1500,
                DiscoveryPenalty           = 700,
                PutPenalty                 = 500,
                CheckForShamPenalty        = 700,
                InformationExchangePenalty = 1000,
                GoalAreaHeight             = 5,
                NumberOfGoals              = 5,
                NumberOfPieces             = 10,
                ShamPieceProbability       = 20
            };

            TcpListener serverSideListener = new TcpListener(IPAddress.Any, config.CsPort);

            serverSideListener.Start();
            TcpClient serverSide = null;
            var       task       = new Task(() => serverSide = serverSideListener.AcceptTcpClient());

            task.Start();


            GameMaster.GameMaster gm = new GameMaster.GameMaster(guiMantainer, config, new ProxyMessageHandler());
            gm.Start();
            guiMantainer.StartGame();
            var gmTask = new Task(() => gm.WaitForEnd());

            gmTask.Start();

            task.Wait();
            serverSideListener.Stop();
            IMessageSenderReceiver senderReceiver = new StreamMessageSenderReceiver(serverSide.GetStream(), new Parser());
            var message = new Message <DiscoveryRequest>()
            {
                AgentId        = 1,
                MessagePayload = new DiscoveryRequest()
            };

            senderReceiver.Send(message);
            senderReceiver.StartReceiving(m =>
            {
                Assert.AreEqual(m.MessageId, MessageType.DiscoveryResponse);
            });
        }
コード例 #6
0
ファイル: GameMaster.cs プロジェクト: tomek1kk/Project-Game
        public void Start()
        {
            _client       = new TcpClient(_gmConfiguration.CsIP, _gmConfiguration.CsPort);
            _communicator = new StreamMessageSenderReceiver(_client.GetStream(), new Parser());
            Log.Information("StreamMessageSenderReceiver started");

            _map = new Map(_gmConfiguration);
            Log.Information("Map created");

            InitGui();
            Log.Information("GUI started");

            _communicator.StartReceiving(GetCSMessage, EndGame);
            Log.Information("Started received messages");
        }
コード例 #7
0
        public void TestCallbackCalledOnParseError()
        {
            Exception receivedException = null;
            Stream    agentToGmStream   = new EchoStream();
            Stream    gmToAgentStream   = new EchoStream();
            Stream    agentSideStream   = new StreamRWJoin(gmToAgentStream, agentToGmStream);
            Stream    gmSideStream      = new StreamRWJoin(agentToGmStream, gmToAgentStream);

            StreamMessageSenderReceiver agentSenderReceiver
                = new StreamMessageSenderReceiver(agentSideStream, new Parser());
            Semaphore semaphore = new Semaphore(0, 100);

            agentSenderReceiver.StartReceiving(message => { }, e =>
                                               { receivedException = e; semaphore.Release(); });

            string messageText = System.Text.Json.JsonSerializer.Serialize(new { a = "abc" });

            byte[] messageBytes       = Encoding.UTF8.GetBytes(messageText);
            byte[] messageLengthBytes = BitConverter.GetBytes((ushort)messageBytes.Length);
            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(messageLengthBytes);
            }

            //when
            gmSideStream.Write(messageLengthBytes, 0, 2);
            gmSideStream.Write(messageBytes, 0, messageBytes.Length);
            semaphore.WaitOne();

            //then
            Assert.IsNotNull(receivedException);
            Assert.IsInstanceOfType(receivedException, typeof(CommunicationLibrary.Exceptions.ParsingException));

            //after
            agentSenderReceiver.Dispose();
            gmSideStream.Close();
            semaphore.Dispose();
        }
コード例 #8
0
        public void TestStreamMessageSenderReceiverCanUseParser()
        {
            Stream stream = new EchoStream();

            Message <JoinGameRequest> expected = new Message <JoinGameRequest>
                                                     (new JoinGameRequest {
                TeamId = "Hello"
            });
            StreamMessageSenderReceiver streamMessageSenderReceiver
                = new StreamMessageSenderReceiver(stream, new Parser());

            BlockingCollection <Message> messages = new BlockingCollection <Message>();

            streamMessageSenderReceiver.StartReceiving(message => messages.Add(message));

            //when
            streamMessageSenderReceiver.Send(expected);
            Message received = messages.Take();

            //then
            Assert.AreEqual(expected.MessagePayload.TeamId,
                            ((Message <JoinGameRequest>)received).MessagePayload.TeamId);
        }
コード例 #9
0
ファイル: Descriptor.cs プロジェクト: tomek1kk/Project-Game
 public virtual void StartReceiving(Action <Message> actionCallback, Action <Exception> errorCallback)
 {
     _streamMessageSenderReceiver.StartReceiving(actionCallback, errorCallback);
 }
コード例 #10
0
        public void TestJoinGameResponse()
        {
            GameStarted defaultGameStartedMessage = new GameStarted
            {
                AgentId   = 0,
                AlliesIds = new List <int> {
                    1
                },
                BoardSize = new BoardSize {
                    X = 10, Y = 10
                },
                EnemiesIds = new List <int> {
                    2, 3
                },
                GoalAreaSize    = 3,
                LeaderId        = 1,
                NumberOfGoals   = 3,
                NumberOfPieces  = 5,
                NumberOfPlayers = new NumberOfPlayers {
                    Allies = 2, Enemies = 2
                },
                Penalties = new Penalties
                {
                    CheckForSham        = "100",
                    DestroyPiece        = "100",
                    Discovery           = "100",
                    InformationExchange = "100",
                    Move     = "100",
                    PutPiece = "100"
                },
                Position = new Position {
                    X = 2, Y = 2
                },
                ShamPieceProbability = 0.5,
                TeamId = "red"
            };

            //gets random free port
            TcpListener serverSideListener = new TcpListener(IPAddress.Any, 0);

            serverSideListener.Start();
            int port = ((IPEndPoint)serverSideListener.LocalEndpoint).Port;

            File.WriteAllText("TMPpath.txt",
                              "{\"CsIP\": \"127.0.0.1\"," +
                              $"\"CsPort\": {port}," +
                              "\"teamID\": \"red\"," +
                              "\"strategy\": 1}");
            string[] args = new string[1] {
                "./TMPpath.txt"
            };
            AgentConfiguration configuration = AgentConfiguration.ReadConfiguration(args);

            TcpClient serverSide = null;
            var       task       = new Task(() => serverSide = serverSideListener.AcceptTcpClient());

            task.Start();

            Agent.Agent agent      = new Agent.Agent(configuration);
            var         listenTask = new Task(() => agent.StartListening());

            listenTask.Start();

            task.Wait();
            serverSideListener.Stop();
            IMessageSenderReceiver senderReceiver = new StreamMessageSenderReceiver(serverSide.GetStream(), new Parser());
            Message joinGameMessage     = null;
            Message exchangeInfoRequest = null;

            Semaphore semaphore = new Semaphore(0, 100);

            senderReceiver.StartReceiving(message =>
            {
                switch (message.MessageId)
                {
                case MessageType.JoinGameRequest:

                    senderReceiver.Send(new Message <JoinGameResponse>(new JoinGameResponse()
                    {
                        AgentID = 1, Accepted = true
                    }));
                    senderReceiver.Send(new Message <GameStarted>(defaultGameStartedMessage));
                    joinGameMessage = message;
                    break;

                default:
                    exchangeInfoRequest = message;
                    semaphore.Release();
                    break;
                }
            });

            semaphore.WaitOne();
            Assert.AreEqual(joinGameMessage.MessageId, MessageType.JoinGameRequest);
            Assert.AreEqual(exchangeInfoRequest.MessageId, MessageType.ExchangeInformationRequest);
        }