예제 #1
0
 public void Connect(int userid)
 {
     if (!ConnectedUsers.Contains(userid))
     {
         ConnectedUsers.Add(userid);
     }
 }
예제 #2
0
        private void ListenToIncommingConnections()
        {
            try
            {
                TcpListener = new TcpListener(ServerLocalIPEP);
                TcpListener.Start();
                while (ServerIsUp)
                {
                    Connection  NewConnection  = new Connection(TcpListener.AcceptTcpClient());
                    UserContext NewUserContext = new UserContext()
                    {
                        Connection = NewConnection, ID = ++ClientIDToken
                    };
                    ConnectedUsers.Add(NewUserContext);
                    NewUserContext.Connection.ConnectionClosedEv += OnClientConnectionClose;


                    if (NewClientConnectedEv != null)
                    {
                        NewClientConnectedEv(this, new ConnectionEventArgs(NewUserContext.Connection));
                    }
                    //Logger.Print("Server got new incomming connection from"+NewConnection.IPAddress +":"+NewConnection.Port);

                    // when new connection established (new client just connected) ,
                    // starts msg listening thread for that connection
                    if (NewUserContext.Connection.IsConnected)
                    {
                        NewUserContext.Connection.ListenForIncMessagesThread = new Thread(NewUserContext.Connection.WaitForMessages);
                        NewUserContext.Connection.ListenForIncMessagesThread.CurrentUICulture = new System.Globalization.CultureInfo("en-us");
                        NewUserContext.Connection.ListenForIncMessagesThread.IsBackground     = true;
                        NewUserContext.Connection.GotMessageEv += GotMessageOnConnection;
                        NewUserContext.Connection.ListenForIncMessagesThread.Name = "ServerListenMessagesOn" + NewUserContext.ID;
                        NewUserContext.Connection.ListenForIncMessagesThread.Start();
                        Logger.Print("INFO: new connection created, connID=" + NewUserContext.ID);
                    }
                    else
                    {
                        Logger.Print("Error: couldnt start listen msgs , tcp connection is not connected");
                    }
                }
            }
            catch (Exception e)
            {
                if (ServerIsUp)
                {
                    Logger.Print("Error: Got Exception [" + e.Message + "] while ServerIsUp=true");
                    // throw e;
                }
            }
            finally
            {
                TcpListener.Stop();
                ServerIsUp = false;
            }
        }
예제 #3
0
 public void AddUser(string user, WebSockUser instance)
 {
     if (!UserExists(user))
     {
         ConnectedUsers.Add(user, instance);
     }
     else
     {
         Logger.LogError("cannot add user \"{0}\"; already added.", user);
     }
 }
예제 #4
0
 private void ChannelOnUserJoined(object sender, IrcChannelUserEventArgs e)
 {
     ExecuteOnUiThread(() =>
     {
         var vm = ConnectedUsers.FirstOrDefault(vmu => vmu.User == e.ChannelUser.User);
         if (vm == null)
         {
             ConnectedUsers.Add(GetUserViewModel(e.ChannelUser.User));
         }
     });
 }
예제 #5
0
        public override void OnWebSocketOpen(WebSocket webSocket)
        {
            User user = new User(webSocket, GenerateName());

            webSocket.OnClose += (object sender, CloseArgs args) => {
                ConnectedUsers.RemoveAll(p => p.webSocket == webSocket);
                SendAll(user.Username + " disconnected");
            };
            webSocket.OnMessageReceived += MessageHandler;
            ConnectedUsers.Add(user);
            SendAll(user.Username + " connected!");
        }
예제 #6
0
        public bool AddUser(User user)
        {
            if (!ConnectedUsers.Contains(user))
            {
                AddMessage($"{user.Name} joined the chat", ChatMessage.ChatMessageTypes.META);

                ConnectedUsers.Add(user);

                return(true);
            }

            return(false);
        }
예제 #7
0
        public void UpdateGuiWithNewMessage(string message)
        {
            //switch thread to GUI thread to write to GUI       // Prof: sorgt dafür, dass der Thread in der GUI ausgeführt wird
            //damit es gleichzeitig abläuft
            //(Dispatcher extra erstellen => Render (Hintergrund) und GUI Threads => aktualisieren GUI)

            App.Current.Dispatcher.Invoke(() =>
            {
                //string name = message;
                string name = message.Split(':')[0];
                string singlemessageWithEnter = message.Split(':')[1];
                string singlemessage          = singlemessageWithEnter.Replace("\r\n", string.Empty);

                string hms = DateTime.Now.ToString("hh:mm:ss");

                bool existingUser = false;
                foreach (var clientuserobj in ConnectedUsers)
                {
                    if (clientuserobj.Username.Equals(name)) //!ConnectedUsers.Username.Contains(name)
                    {                                        //not in list => add it
                        existingUser = true;

                        clientuserobj.singleUserMessage.Add(singlemessage);
                        clientuserobj.userTimestamp.Add(hms);
                    }
                }

                if (!existingUser)
                {
                    ObservableCollection <string> prepsingleUserMessage = new ObservableCollection <string>();
                    ObservableCollection <string> prepuserTimestamp     = new ObservableCollection <string>();
                    prepsingleUserMessage.Add(singlemessage);
                    prepuserTimestamp.Add(hms);

                    ConnectedUsers.Add(new ClientUser()
                    {
                        Username          = name,
                        singleUserMessage = prepsingleUserMessage,
                        userTimestamp     = prepuserTimestamp
                    });
                }

                //neue Nachricht zu Nachrichten-Collection hinzufügen
                Chatmessages.Add(name + ": " + singlemessage);

                // GUI informieren, dass Nachrichtenanzahl gestiegen ist
                RaisePropertyChanged("ConnectedUsers");
                RaisePropertyChanged("Chatmessages");
            });
        }
예제 #8
0
        public override async Task OnConnectedAsync()
        {
            var    username = Context.GetHttpContext().Request.Query["username"];
            string roomToken;
            Room   room;

            if (Context.GetHttpContext().Request.Query.ContainsKey("room"))
            {
                roomToken = Context.GetHttpContext().Request.Query["room"];
                room      = OnlineRooms.FirstOrDefault(r => r.Name == roomToken);
                if (room == null)
                {
                    room              = new Room();
                    room.Name         = roomToken;
                    room.WaitingUsers = new List <Client>();
                    room.ReadyUsers   = new List <Client>();
                    OnlineRooms.Add(room);
                }
            }
            else
            {
                Random       rnd   = new Random();
                const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                roomToken = new string(Enumerable.Repeat(chars, 3)
                                       .Select(s => s[rnd.Next(s.Length)]).ToArray());
                room              = new Room();
                room.Name         = roomToken;
                room.WaitingUsers = new List <Client>();
                room.ReadyUsers   = new List <Client>();
                OnlineRooms.Add(room);
            }


            Client c = new Client()
            {
                Usuario = username,
                ID      = Context.ConnectionId,
                Room    = room
            };

            ConnectedUsers.Add(c);
            c.Room.WaitingUsers.Add(c);
            await Groups.AddToGroupAsync(c.ID, c.Room.Name);

            await Clients.Group(c.Room.Name).SendAsync("roomToken", c.Room.Name);

            await Clients.Group(c.Room.Name).SendAsync("updateUsers", c.Room.WaitingUsers.Count, c.Room.WaitingUsers.Select(u => u.Usuario));

            await Clients.Group(c.Room.Name).SendAsync("updateReadyUsers", c.Room.WaitingUsers.Count + c.Room.ReadyUsers.Count, c.Room.ReadyUsers.Count, c.Room.ReadyUsers.Select(u => u.Usuario), c.Room.game);
        }
예제 #9
0
        public IActionResult Connect()
        {
            if (ConnectedUsers.Any(x => x.ConnectionId.Equals(Context.ConnectionId)))
            {
                throw new InvalidOperationException(Resources.UserIsConnected);
            }

            var user = CallApiGET <UserResponseDTO>(uri: "api/users", isSecured: true);

            user.ConnectionId = Context.ConnectionId;

            ConnectedUsers.Add(user);

            return(new OkResult());
        }
예제 #10
0
파일: AppHub.cs 프로젝트: abisevilla/chat
        public void AddUser(Client c)
        {
            ConnectedUsers.Add(c);

            Clients.All.updateUsers(ConnectedUsers.Count(), ConnectedUsers.Select(u => u.NickName));

            using (var db = new AppDbContext())
            {
                var user = new User()
                {
                    NickName = c.NickName
                };
                db.Users.Add(user);
                db.SaveChanges();
            }
        }
예제 #11
0
        public HostServerViewModel(INetworkInteractionFactory networkInteractionFactory, IEventAggregator eventAggregator, INetworkService networkService, IPlayServerService playServerService)
        {
            _networkInteractionFactory = networkInteractionFactory;
            _eventAggregator           = eventAggregator;
            _networkService            = networkService;
            _playServerService         = playServerService;

            playServerService.ClientConnected    += (sender, e) => ConnectedUsers.Add(e.Address);
            playServerService.ClientDisconnected += (sender, e) => ConnectedUsers.Remove(e.Address);

            Task.Run(async() => await networkService.ConfigureMachineForHosting().ContinueWith(task =>
            {
                HostAddress = new NetworkAddress(networkService.ExternalIp, networkService.Port);
                IsLoading   = false;
            }));
        }
예제 #12
0
        // TODO: Add user list
        public static void OnUserConnect(IAsyncResult ar)
        {
            SausageConnection user;

            try
            {
                user = new SausageConnection(MainSocket.EndAccept(ar));
            }
            catch (SocketException ex)
            {
                Close();
                return;
            }
            catch (ObjectDisposedException ex)
            {
                return;
            }
            if (!Blacklisted.Any(x => x == user.Ip.Address))
            {
                UiCtx.Send(x => ConnectedUsers.Add(user));
                UiCtx.Send(x => Vm.ConnectedUsers = SortUsersList());
                UiCtx.Send(x => Vm.Messages.Add(new ServerMessage($"{user} has connected")));
                UiCtx.Send(x => Mw.AddTextToDebugBox($"User connected on {user.Ip}\n"));
                // global packet for all the users to know the user has joined
                PacketFormat GlobalPacket = new PacketFormat(PacketOption.UserConnected)
                {
                    Guid    = user.UserInfo.Guid,
                    NewName = user.UserInfo.Name
                };
                // local packet for the user (who joined) to get his GUID
                PacketFormat LocalPacket = new PacketFormat(PacketOption.GetGuid)
                {
                    Guid      = user.UserInfo.Guid,
                    UsersList = UsersDictionary.ToArray()
                };
                UsersDictionary.Add(user.UserInfo);
                user.SendAsync(LocalPacket);
                Log(GlobalPacket, user);
            }
            else
            {
                // doesn't log if the user is blacklisted
                user.Disconnect();
            }
            MainSocket.BeginAccept(OnUserConnect, null);
        }
예제 #13
0
        /// <summary>
        /// To be called when a new User Connects, Notifies other users that a new User is Connected
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public void Connect(string name)
        {
            var id = Context.ConnectionId;

            if (ConnectedUsers == null)
            {
                ConnectedUsers = new HashSet <iUser>();
            }
            if (ConnectedUsers.Count(x => x.ID == id) == 0)
            {
                ConnectedUsers.Add(new iUser()
                {
                    ID = id, Name = name
                });
                Clients.Caller.onConnected(id, name, ConnectedUsers.Where(x => x.ID != id));
                Clients.AllExcept(id).onNewUserConnected(id, name);
            }
        }
예제 #14
0
 private void ClientSubscribed(User user)
 {
     try
     {
         this._currentDispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
         {
             if (!ConnectedUsers.Contains(user))
             {
                 ConnectedUsers.Add(user);
                 ConnectedUsersCount++;
             }
         }));
     }
     catch (Exception exception)
     {
         Logger.Error(exception, OType.FullName, "ClientSubscribed");
     }
 }
예제 #15
0
 private void E_ReceivedMsg(object sender, string e)
 {
     if (e.StartsWith("@quit"))
     {
         var client = sender as ClientHandler;
         ConnectedUsers.Remove(client.Username); // remove username
     }
     else
     {
         App.Current.Dispatcher.Invoke(() =>
         {
             var client = sender as ClientHandler;
             ReceivedMsg.Add(client.Username + ":" + e);
             RaisePropertyChanged(nameof(CountMsg));
             if (!ConnectedUsers.Contains(client.Username))
             {
                 ConnectedUsers.Add(client.Username);
             }
         });
     }
 }
예제 #16
0
        public async Task <IActionResult> Connect(string userName, bool isHolding)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrWhiteSpace(userName))
            {
                throw new InvalidDataException(Resources.InvalidUserName);
            }

            if (ConnectedUsers.Any(x => x.ConnectionId.Equals(Context.ConnectionId)))
            {
                throw new InvalidOperationException(Resources.UserIsConnected);
            }

            var user = new UserDetail
            {
                UserId       = Guid.NewGuid(),
                ConnectionId = Context.ConnectionId,
                UserName     = userName,
                IsOnHold     = isHolding
            };

            ConnectedUsers.Add(user);

            if (user.IsOnHold)
            {
                // send to all except caller client
                await Clients.AllExcept(user.ConnectionId)
                .SendAsync(ChatHubMethods.NewUserAvailable, new
                {
                    userId       = user.UserId,
                    userName     = user.UserName,
                    messageCount = 0
                });
            }

            return(new OkObjectResult(user.UserId));
        }
예제 #17
0
파일: NebulaServer.cs 프로젝트: wwwK/Nebula
 public override void OnPeerConnected(NetPeer peer)
 {
     ConnectedUsers.Add(peer.Id, new NebulaUser(peer));
     WriteLine($"Client Connected '{peer.EndPoint.Address}:{peer.EndPoint.Port}'", ConsoleColor.Cyan);
 }
예제 #18
0
        void WorkerOnProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Message message = e.UserState as Message;

            if (message != null)
            {
                switch (message.Type)
                {
                case Message.MessageType.Connect:
                {
                    if (message.Username.Equals(Username))
                    {
                        ChatMessages += String.Format("({1}) Welcome, {0}!\n", Username, message.MessageCreationTime.ToString("G"));
                        IsConnected   = true;
                    }
                    else
                    {
                        ConnectedUsers.Add(message.Username);
                        ChatMessages += String.Format("({1}) {0} has joined the server.\n", message.Username, message.MessageCreationTime.ToString("G"));
                    }
                    break;
                }

                case Message.MessageType.Disconnect:
                {
                    if (!message.Username.Equals(Username))
                    {
                        ConnectedUsers.Remove(message.Username);
                        ChatMessages += String.Format("({1}) {0} has left the server.\n", message.Username, message.MessageCreationTime.ToString("G"));
                    }
                    break;
                }

                case Message.MessageType.ChatMessage:
                {
                    if (message.Username != Username && !ConnectedUsers.Contains(message.Username))
                    {
                        ConnectedUsers.Add(message.Username);
                    }

                    ChatMessages += String.Format("({1}) {2}: {0} \n", message.ChatMessage, message.MessageCreationTime.ToString("G"), message.Username);
                    break;
                }

                case Message.MessageType.UsernameAlreadyTaken:
                {
                    ChatMessages += String.Format("({1}) Username {0} is already taken!\n", Username, message.MessageCreationTime.ToString("G"));

                    _networkStream.Close();
                    _tcpClient.Close();
                    _tcpClient = new TcpClient();
                    _worker.CancelAsync();

                    break;
                }

                default:
                    //do nothing
                    break;
                }
            }
        }
예제 #19
0
 public void AddConectedUser(User user)
 {
     ConnectedUsers.Add(user);
 }
예제 #20
0
 protected internal virtual void OnClientConnected(TUser user)
 {
     ConnectedUsers.Add(user);
 }
예제 #21
0
 public void AddConnectedUser(string ConnectionId, string userName)
 {
     ConnectedUsers.Add(ConnectionId, userName);
 }
예제 #22
0
 /// <summary>
 /// Occurs each time the event 'UserConnected' raised!
 /// Event does: Adds the new user to the connected users list!
 /// </summary>
 /// <param name="user">The user connected</param>
 private void OnUserConnected(UserLogin user)
 {
     ConnectedUsers.Add(user); // Adds the new user to the connected list!
 }
예제 #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BindableChannel"/> class.
        /// </summary>
        /// <param name="model">API Channel Model.</param>
        /// <param name="guildId">Id of Channel's guild.</param>
        /// <param name="states">List of VoiceStates for users in a voice channel.</param>
        public BindableChannel([NotNull] Channel model, [CanBeNull] IEnumerable<VoiceState> states = null) : base(model)
        {
            MessengerInstance.Register<GatewayUserGuildSettingsUpdatedMessage>(this, m =>
            {
                if ((m.Settings.GuildId ?? "DM") == GuildId)
                {
                    DispatcherHelper.CheckBeginInvokeOnUi(() =>
                    {
                        // Updated channel settings
                        ChannelOverride channelOverride = ChannelsService.GetChannelSettings(Model.Id);
                        if (channelOverride != null)
                        {
                            Muted = channelOverride.Muted;
                        }
                    });
                }
            });

            MessengerInstance.Register<SettingChangedMessage<bool>>(this, m =>
            {
                if (m.Key == SettingKeys.ShowNoPermssions)
                {
                    RaisePropertyChanged(nameof(Hidden));
                }
            });

            MessengerInstance.Register<SettingChangedMessage<CollapseOverride>>(this, m =>
            {
                if (m.Key == SettingKeys.CollapseOverride)
                {
                    RaisePropertyChanged(nameof(Hidden));
                }
            });

            MessengerInstance.Register<SpeakMessage>(this, e =>
            {
                if (e.EventData.UserId != null && ConnectedUsers.ContainsKey(e.EventData.UserId))
                {
                    DispatcherHelper.CheckBeginInvokeOnUi(() => { ConnectedUsers[e.EventData.UserId].Speaking = e.EventData.Speaking > 0; });
                }
            });

            MessengerInstance.Register<GatewayVoiceStateUpdateMessage>(this, m =>
            {
                DispatcherHelper.CheckBeginInvokeOnUi(() =>
                {
                    if (m.VoiceState.ChannelId == Model.Id)
                    {
                        if (ConnectedUsers.ContainsKey(m.VoiceState.UserId))
                        {
                            ConnectedUsers[m.VoiceState.UserId].Model = m.VoiceState;
                            ConnectedUsers[m.VoiceState.UserId].UpateProperties();
                        }
                        else
                        {
                            ConnectedUsers.Add(m.VoiceState.UserId, new BindableVoiceUser(m.VoiceState));
                        }
                    }
                    else if (ConnectedUsers.ContainsKey(m.VoiceState.UserId))
                    {
                        ConnectedUsers.Remove(m.VoiceState.UserId);
                    }
                });
            });

            if (states != null)
            {
                foreach (var state in states)
                {
                    if (state.ChannelId == Model.Id)
                    {
                        state.GuildId = GuildId;
                        ConnectedUsers.Add(state.UserId, new BindableVoiceUser(state));
                    }
                }
            }
        }