public void Connect(int userid) { if (!ConnectedUsers.Contains(userid)) { ConnectedUsers.Add(userid); } }
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; } }
public void AddUser(string user, WebSockUser instance) { if (!UserExists(user)) { ConnectedUsers.Add(user, instance); } else { Logger.LogError("cannot add user \"{0}\"; already added.", user); } }
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)); } }); }
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!"); }
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); }
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"); }); }
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); }
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()); }
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(); } }
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; })); }
// 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); }
/// <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); } }
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"); } }
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); } }); } }
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)); }
public override void OnPeerConnected(NetPeer peer) { ConnectedUsers.Add(peer.Id, new NebulaUser(peer)); WriteLine($"Client Connected '{peer.EndPoint.Address}:{peer.EndPoint.Port}'", ConsoleColor.Cyan); }
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; } } }
public void AddConectedUser(User user) { ConnectedUsers.Add(user); }
protected internal virtual void OnClientConnected(TUser user) { ConnectedUsers.Add(user); }
public void AddConnectedUser(string ConnectionId, string userName) { ConnectedUsers.Add(ConnectionId, userName); }
/// <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! }
/// <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)); } } } }