public void Start() { int currentId = Constants.FirstUserId; TcpListener ServerSocket = new TcpListener(IPAddress.Any, Port); ServerSocket.Start(); Logger.Info($"Server \"{ServerUser.Name}\" started at {GlobalIPAddress.GetGlobalIPAddress()}:{Port}"); while (true) { TcpClient client = ServerSocket.AcceptTcpClient(); var chatClient = ChatClient.Create(currentId, client); chatClient.Locker = Locker; lock (Locker) Clients.Add(chatClient); ChatMail.SendMessage(ChatMessage.Create(MessageCode.ServerName, ServerUser, new ChatUser(currentId), DateTime.Now, ChatMessageText.CreateEmpty()), currentId); Logger.Info($"#{currentId} connected!"); Thread t = new Thread(HandleClients); t.Start(currentId); currentId += Constants.UserIdIncrementValue; } }
private void OnRegistration(ChatMessage message) { Logger.Debug($"Registration new user: {message.Sender.Name}."); Clients[message.Sender.Id].Name = message.Sender.Name; ChatMail.SendMessage(ChatMessage.Create(MessageCode.NewUser, ServerUser, null, DateTime.Now, ChatMessageText.Create(message.Sender.ToString()))); ChatMail.SendMessage(ChatMessage.Create(MessageCode.ServerUsers, ServerUser, message.Sender, DateTime.Now, ChatMessageText.Create(String.Join(" ", Clients.RegestredUsers.Where(user => user.Id != message.Sender.Id).Select(user => user.User)))), message.Sender.Id); }
private void OnNewUserMessage(ChatMessage message) { if (message.Recipient is null) { throw new ArgumentException(nameof(message)); } if (!message.Sender.Equals(message.Recipient)) { ChatMail.SendMessage(ChatMessage.Create(MessageCode.RepeatMessage, message.Sender, message.Recipient, message.Date, message.Message), message.Sender.Id); } ChatMail.SendMessage(message, message.Recipient.Id); }
private void HandleClients(object clientId) { int id = (int)clientId; TcpClient client; lock (Locker) client = (Clients[id] as ChatClient)?.Client; try { while (true) { NetworkStream stream = client.GetStream(); byte[] buffer = new byte[Constants.MessageSize]; int byte_count = stream.Read(buffer, 0, buffer.Length); if (byte_count == 0) { break; } string data = Encoding.UTF8.GetString(buffer, 0, byte_count); HandleMessage(ChatMessage.Parse(data)); } } catch (Exception e) { Logger.Error(e.Message); Logger.Error($"Error: #{id} lost connection."); } finally { lock (Locker) Clients.Remove(id); ChatMail.SendMessage(ChatMessage.Create(MessageCode.UserLeave, ServerUser, null, DateTime.Now, ChatMessageText.Create(id.ToString()))); Logger.Info($"#{id} has left."); client.Client.Shutdown(SocketShutdown.Both); client.Close(); } }
private void OnNewUserPublicMessage(ChatMessage message) { ChatMail.SendMessage(message); }