示例#1
0
        public void Send(IEventMessage message)
        {
            var eventBuilder = EventBuilder.Build(message);
            var data         = eventBuilder.ToByteArray();

            this.Client.Send(data, data.Length);
        }
        public void Reply(IEventMessage message, IPEndPoint endpoint)
        {
            var ev   = EventBuilder.Build(message);
            var data = ev.ToByteArray();

            this.Client.Send(data, data.Length, endpoint);
        }
示例#3
0
        public async Task ReceiveAsync()
        {
            var received = await this.Client.ReceiveAsync();

            var eventBuilder = EventBuilder.Build(received.Buffer);

            this._eventProcessor.Process(eventBuilder.Event);
        }
示例#4
0
        private void OnMessageSent(ChatMessageMessage message, DateTime timestamp)
        {
            this._chatManager.SendMessage(this._warsimUser, this._channel, DateTime.Now, message.Content);

            message.UserId   = this._warsimUser.UserId;
            message.Username = this._warsimUser.Username;

            this.BroadcastToChannel(EventBuilder.Build(message).Serialize());
        }
        protected override void OnWebSocketClose(CloseEventArgs e)
        {
            this._warsimUser.GameHostWebSocketId = string.Empty;
            this._warsimUser.ActiveGameId        = Guid.Empty;

            // Owner has manually ended the game, the game is already erased from memory
            if (e.Code == 2008)
            {
                return;
            }

            // If the user is a spectator
            if (this._gameHost.Spectators.ContainsKey(this._warsimUser.UserId))
            {
                this._gameHost.Spectators.TryRemove(this._warsimUser.UserId, out this._warsimUser);
            }

            // If the user is a player
            var oldGameOwnerId  = this._gameHost.OwnerId;
            var gameStillActive = this._gameHost.Leave(this._warsimUser);

            if (gameStillActive)
            {
                this._gameHost.Map.ResetStartArrow(this._warsimUser.UserId);
                this._gameHost.Map.DeselectUserObjects(this._warsimUser.UserId);

                if (this._gameHost.Mode == GameMode.Simulation)
                {
                    this._gameHost.Map.RemoveUserRobot(this._warsimUser.UserId);
                }

                var disconnectedMsg = new PlayerDisconnectedMessage
                {
                    UserId   = this._warsimUser.UserId,
                    Username = this._warsimUser.Username
                };

                this.BroadcastToCurrentGame(EventBuilder.Build(disconnectedMsg).Serialize());

                // This means the owner of the game has changed
                if (oldGameOwnerId == this._warsimUser.UserId)
                {
                    var newOwnerMsg = new NewGameOwnerMessage();
                    var newOwner    = this._gameManager.GetUser(this._gameHost.OwnerId);

                    // Send a message to tell the new game owner
                    this.Sessions.SendTo(EventBuilder.Build(newOwnerMsg).Serialize(), newOwner.GameHostWebSocketId);
                }
            }
            else
            {
                this._gameManager.EndGame(this._gameHost);
            }
        }
        private void OnGamePause(PauseGameMessage msg, DateTime timestamp)
        {
            if (!this.IsGameOwner())
            {
                return;
            }

            this._gameHost.IsPaused = msg.IsPaused;

            this.BroadcastToCurrentGame(EventBuilder.Build(msg).Serialize());
        }
        public async Task ReceiveAsync()
        {
            var received = await this.Client.ReceiveAsync();

            var eventBuilder = EventBuilder.Build(received.Buffer);

            if (!endPoints.Contains(received.RemoteEndPoint))
            {
                endPoints.Add(received.RemoteEndPoint);
            }

            this._eventProcessor.Process(eventBuilder.Event);
        }
示例#8
0
        public string Serialize(Contract contract, string template, List <Contract> contracts)
        {
            var nodes = NodeHelper.GetEvents(contract).ToList();

            if (!nodes.Any())
            {
                return(template.Replace("{{Events}}", string.Empty));
            }

            var builder = new EventBuilder(nodes);

            template = template.Replace("{{Events}}", builder.Build());
            return(template);
        }
示例#9
0
 private void SendWebSocketNotification(string userId, IEventMessage message)
 {
     try
     {
         this._gameManager.WebSocketServices.SendTo(
             GameManager.UserWsPath,
             EventBuilder.Build(message).Serialize(),
             this._gameManager.GetUser(userId).UserWebSocketId
             );
     }
     catch
     {
         // ignored
     }
 }
示例#10
0
        protected override void OnWebSocketClose(CloseEventArgs e)
        {
            // Close all websocket connections if the user websocket connection is closed
            this._gameManager.WebSocketServices.GetSessions(GameManager.ChatWsPath).CloseSession(this._warsimUser.ChatWebSocketId);
            this._gameManager.WebSocketServices.GetSessions(GameManager.GameHostWsPath).CloseSession(this._warsimUser.GameHostWebSocketId);
            this._gameManager.WebSocketServices.GetSessions(GameManager.LocalGameWsPath).CloseSession(this._warsimUser.LocalGameWebSocketId);

            var ev = EventBuilder.Build(new UserDisconnectedMessage
            {
                UserId = this._warsimUser.UserId
            });

            this.Sessions.Broadcast(ev.Serialize());

            this._userManager.DisconnectUser(this._warsimUser.UserId);
        }
        private void OnGameModeSwitch(GameModeSwitchMessage msg, DateTime timestamp)
        {
            if (!this.IsGameOwner())
            {
                return;
            }

            this._gameHost.Mode = msg.Mode;

            if (msg.Mode == GameMode.Edition)
            {
                this._gameHost.Map.RemoveRobots();
                this._gameHost.Map.DeselectAllObjects();
            }

            this.BroadcastToCurrentGame(EventBuilder.Build(msg).Serialize());
        }
示例#12
0
        protected override void OnWebSocketOpen()
        {
            var userToken       = JwtHelper.DecodeToken(this.Context.QueryString.Get("auth_token"));
            var channelIdString = this.Context.QueryString.Get("channel_id");

            Guid channelId;

            // If invalid token, close the connection
            if (userToken == null || string.IsNullOrEmpty(channelIdString) || !Guid.TryParse(channelIdString, out channelId))
            {
                this.Sessions.CloseSession(this.ID, 2000, "Invalid query parameters");
                return;
            }

            try
            {
                this._warsimUser = this._gameManager.GetUser(userToken.UserId);
            }
            catch
            {
                this.Sessions.CloseSession(this.ID, 2001, "This user isn't connected");
                return;
            }

            this._channel = this._chatManager.JoinChannel(this._warsimUser, channelId);

            this._warsimUser.ChatWebSocketId = this.ID;
            this._warsimUser.ActiveChannelId = channelId;

            // Send current channel state to new user
            this.Send(EventBuilder.Build(new ChannelStateMessage
            {
                ActiveUsers = this._channel.ActiveUsers.Select(WarsimClientUser.Map).ToList(),
                Messages    = this._channel.Messages
            }).Serialize());

            this.BroadcastToChannel(EventBuilder.Build(new UserJoinedChannelMessage
            {
                UserId   = this._warsimUser.UserId,
                Username = this._warsimUser.Username
            }).Serialize());
        }
示例#13
0
        public EventWrapper <TEvent> Write <TEvent>(Expression <Action <EventBuilder <TEvent> > > buildExpr) where TEvent : IEvent
        {
            var builder = new EventBuilder <TEvent>();
            var action  = buildExpr.Compile();

            action(builder);

            var evt = builder.Build();

            evt.EventDate = DateTime.UtcNow;
            evt.EventId   = _GuidGenerator.Generate();
            evt.StreamId  = _StreamId;

            Events.Add(evt);
            PersistEvent(evt);

            _Mediator.Publish(builder.Event);

            return(evt);
        }
示例#14
0
        protected override void OnWebSocketClose(CloseEventArgs e)
        {
            // If the channel has been closed
            if (this._chatManager.GetChannelById(this._channel.Id) == null)
            {
                return;
            }

            this._chatManager.LeaveChannel(this._warsimUser, this._channel.Id);

            var leftChannelEvent = EventBuilder.Build(new UserLeftChannelMessage
            {
                UserId   = this._warsimUser.UserId,
                Username = this._warsimUser.Username
            });

            this.BroadcastToChannel(leftChannelEvent.Serialize());

            this._warsimUser.ChatWebSocketId = string.Empty;
            this._warsimUser.ActiveChannelId = Guid.Empty;
        }
示例#15
0
        private static void Create_channel_then_join_then_send_message()
        {
            WaitFor("Create channel");

            var postData = new ChatCreatePublicChannelMessage {
                ChannelName = "Channel de test", ParticipantsIds = new List <string>()
            };
            var result = HttpRequestHelper.PostAsync("http://127.0.0.1:4321/api/chat/channel", postData, Token).Result;

            var channelId = JsonConvert.DeserializeObject <Guid>(result.Content.ReadAsStringAsync().Result);

            WaitFor("Join channel");

            var chatWebSocket = new WebSocketClient($"ws://127.0.0.1:6789/Chat?auth_token={Token}&channel_id={channelId}");

            chatWebSocket.RegisterHandler((UserJoinedChannelMessage msg, DateTime timestamp) =>
            {
                Console.WriteLine($"Utilisateur connecté {msg.Username}");
            });
            chatWebSocket.OnCloseHandler = (o, args) =>
            {
                Console.WriteLine($"{args.Code}: {args.Reason}");
            };

            chatWebSocket.Connect();

            WaitFor("Send chat message");

            chatWebSocket.Send(EventBuilder.Build(new ChatMessageMessage
            {
                Content = "Hello channel!"
            }).Serialize());

            WaitFor("Exit channel");
            chatWebSocket.Close();
        }
示例#16
0
        protected override void OnWebSocketOpen()
        {
            var userToken = JwtHelper.DecodeToken(this.Context.QueryString.Get("auth_token"));
            var udpPort   = this.Context.QueryString.Get("udp_port");

            // If invalid query parameters, close the connection
            if (userToken == null || string.IsNullOrEmpty(udpPort))
            {
                this.Sessions.CloseSession(this.ID, 2000, "Invalid query parameters");
                return;
            }

            // Add user to connected users
            if (this._userManager.Users.ContainsKey(userToken.UserId))
            {
                this.Sessions.CloseSession(this.ID, 2001, "User already connected");
                return;
            }

            this._warsimUser = this._userManager.ConnectUser(userToken.UserId, userToken.Username);
            this._warsimUser.UserWebSocketId = this.ID;

            // Save user UDP endpoint
            this._warsimUser.GameUdpEndPoint = new IPEndPoint(
                this.Context.UserEndPoint.Address,
                int.Parse(udpPort));

            // User has now connected to the game and is visible to other users
            var ev = EventBuilder.Build(new UserConnectedMessage
            {
                UserId   = this._warsimUser.UserId,
                Username = this._warsimUser.Username
            });

            this.Sessions.Broadcast(ev.Serialize());
        }
示例#17
0
        protected override void OnWebSocketOpen()
        {
            var userToken   = JwtHelper.DecodeToken(this.Context.QueryString.Get("auth_token"));
            var mapIdString = this.Context.QueryString.Get("map_id");

            Guid mapId;

            if (userToken == null || string.IsNullOrEmpty(mapIdString) || !Guid.TryParse(mapIdString, out mapId))
            {
                this.Sessions.CloseSession(this.ID, 2000, "Invalid query parameters");
                return;
            }

            this._warsimUser = this._gameManager.GetUser(userToken.UserId);

            if (this._warsimUser == null)
            {
                this.Sessions.CloseSession(this.ID, 2001, "This user isn't connected");
                return;
            }

            var mapRepo = new MapRepository(new ApplicationDbContext());

            var map = mapRepo.GetMapById(mapId);

            if (map == null)
            {
                this.Sessions.CloseSession(this.ID, 2002, "This map doesn't exist");
                return;
            }

            var password = this.Context.QueryString.Get("map_password");

            if (!map.ValidatePassword(password))
            {
                this.Sessions.CloseSession(this.ID, 2003, "Wrong map password");
                return;
            }

            if (map.IsLocked)
            {
                this.Sessions.CloseSession(this.ID, 2004, "This map is locked");
                return;
            }

            this._localGame = new LocalGame
            {
                Map    = map,
                UserId = this._warsimUser.UserId
            };

            this._warsimUser.LocalGameWebSocketId = this.ID;
            this._gameManager.StartLocalGame(this._localGame);

            var localGameState = new LocalGameStateMessage
            {
                SceneObjects = map.SceneObjects
            };

            this.Sessions.SendTo(EventBuilder.Build(localGameState).Serialize(), this._warsimUser.LocalGameWebSocketId);
        }
示例#18
0
 public void BuildEvent(EventBuilder builder)
 {
     builder.Build(
         this.eventId,
         this.eventTitle,
         this.eventStart,
         this.eventEnd,
         this.isOwner,
         this.isDelegate,
         this.isAuthoriser,
         this.isPrivateEvent,
         this.eventType);
 }
        protected override void OnWebSocketOpen()
        {
            var userToken    = JwtHelper.DecodeToken(this.Context.QueryString.Get("auth_token"));
            var gameIdString = this.Context.QueryString.Get("game_id");

            Guid gameId;

            if (userToken == null || string.IsNullOrEmpty(gameIdString) || !Guid.TryParse(gameIdString, out gameId))
            {
                this.Sessions.CloseSession(this.ID, 2000, "Invalid query parameters");
                return;
            }

            if (!this._gameManager.GameHosts.ContainsKey(gameId))
            {
                this.Sessions.CloseSession(this.ID, 2001, "This game doesn't exist");
                return;
            }

            this._gameHost   = this._gameManager.GameHosts[gameId];
            this._warsimUser = this._gameManager.GetUser(userToken.UserId);

            if (this._warsimUser == null)
            {
                this.Sessions.CloseSession(this.ID, 2002, "This user isn't connected");
                return;
            }

            var password   = this.Context.QueryString.Get("game_password");
            var playerType = this.Context.QueryString.Get("player_type");

            if (playerType == "spectator")
            {
                // Start spectating, without telling other players
                try
                {
                    this._gameHost.Spectate(this._warsimUser, password);
                }
                catch (GameException e)
                {
                    this.Sessions.CloseSession(this.ID, e.Code, e.Message);
                    return;
                }
            }
            else
            {
                try
                {
                    this._gameHost.Join(this._warsimUser, password);
                }
                catch (GameException e)
                {
                    this.Sessions.CloseSession(this.ID, e.Code, e.Message);
                    return;
                }

                var msg = new PlayerConnectedMessage
                {
                    UserId   = this._warsimUser.UserId,
                    Username = this._warsimUser.Username
                };

                this.BroadcastToCurrentGame(EventBuilder.Build(msg).Serialize());
            }

            var statsUpdate = new GameStatisticsUpdate {
                UserId = this._warsimUser.UserId
            };

            if (this.IsGameOwner())
            {
                statsUpdate.GameCreatedCount++;
            }
            else
            {
                statsUpdate.GameJoinedCount++;
            }

            new UserRepository(new ApplicationDbContext()).UpdateUserStatistics(statsUpdate);

            this._warsimUser.GameHostWebSocketId = this.ID;
            this._warsimUser.ActiveGameId        = this._gameHost.Id;
        }