Ejemplo n.º 1
0
        public void Listen()
        {
            UdpClient client = new UdpClient
            {
                ExclusiveAddressUse = false
            };
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 2222);

            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            client.Client.Bind(localEP);

            client.JoinMulticastGroup(_ipAddress);

            string formatted_data;

            while (true)
            {
                Byte[] data = client.Receive(ref localEP);
                formatted_data = Encoding.UTF8.GetString(data);
                MessageReceive.Invoke(this, new MessageReceiveEventArgs {
                    Message = new Message(formatted_data, DateTime.Now)
                });
            }
        }
Ejemplo n.º 2
0
        /// <inheritdoc/>
        public bool TrySetUsername(string username)
        {
            SendMessage($"Login:{username}");
            try
            {
                string message = ReadMessage();
                if (message.Contains("joined the chat."))
                {
                    Username = username;
                    return(true);
                }

                MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                    Message = new Message(message, DateTime.Now)
                });
            }
            catch
            {
                MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                    Message = new Message("Server disconnected.", DateTime.Now)
                });
                Close();
            }
            return(false);
        }
Ejemplo n.º 3
0
        private void StreamRead(IAsyncResult ar)
        {
            try
            {
                int result = _stream.EndRead(ar);
                if (result > 0)
                {
                    //_log.WriteLine($"Received {result} bytes !");
                    var cmd = Command.Parse(_buffer, 0, result);
                    switch (cmd.CmdType)
                    {
                    case Command.CommandType.Ping:
                    {
                        SendCommand(new Command(Command.CommandType.Ping, new byte[] { 1 }));
                    }
                    break;

                    case Command.CommandType.GetVersion:
                        break;

                    case Command.CommandType.CreateUser:
                    {
                        int errcode = BitConverter.ToInt32(cmd.Data);
                        if (errcode == (int)CreateUserError.Success)
                        {
                            SendCommand(new Command(Command.CommandType.GetUserInfo, Encoding.UTF8.GetBytes(CurrentUser.Tag)));
                        }
                        CreateUserCallBack?.Invoke(this, new CreateUserEventArgs((CreateUserError)errcode));
                    }
                    break;

                    case Command.CommandType.Message:
                    {
                        Message msg = Message.Parse(cmd.Data);
                        MessageReceive?.Invoke(this, new MessageReceiveEventArgs(msg));
                    }
                    break;

                    case Command.CommandType.GetUserInfo:
                    {
                        User usr = User.Parse(cmd.Data);
                        if (usr.Tag == CurrentUser.Tag)
                        {
                            this.usr = usr;
                        }
                        UserInfoReceive?.Invoke(this, new UserInfoReceiveEventArgs(usr));
                    }
                    break;
                    }
                }
            }
            catch (Exception ex)
            {
                _log.WriteLine(ex.ToString());
            }
            _stream.BeginRead(_buffer, 0, _buffer.Length, StreamRead, ar.AsyncState);
        }
Ejemplo n.º 4
0
 /// <inheritdoc/>
 public void Process()
 {
     while (IsActive)
     {
         try
         {
             string message = ReadMessage();
             MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                 Message = new Message(message, DateTime.Now)
             });
         }
         catch (Exception e)
         {
             MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                 Message = new Message("Server disconnected.", DateTime.Now)
             });
             Close();
             break;
         }
     }
 }
Ejemplo n.º 5
0
        /// <inheritdoc/>
        public void Process(object chatClient)
        {
            var client = chatClient as ChatClient;

            LoginNewClient(client);

            while (client.IsActive)
            {
                try
                {
                    var messageText = client.ReadMessage();
                    var message     = new Message(messageText, DateTime.Now);
                    MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                        Message = message
                    });
                    BroadcastMessage(messageText);
                    History.AddNewMessage(message);
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode != SocketError.ConnectionAborted && e.SocketErrorCode != SocketError.ConnectionReset)
                    {
                        throw e;
                    }

                    Clients.Remove(client);
                    var message = new Message($"{client.Username} left the chat.", DateTime.Now);
                    MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                        Message = message
                    });
                    BroadcastMessage(message.Text);
                    History.AddNewMessage(message);
                    break;
                }
            }
        }
Ejemplo n.º 6
0
 protected void recieve(object sender, EventArgs e)
 {
     MessageReceive?.Invoke(sender, e);
 }
Ejemplo n.º 7
0
        private void LoginNewClient(ChatClient client)
        {
            while (client.IsActive)
            {
                var messageText = client.ReadMessage();
                var username    = messageText.Replace("Login:"******"");

                if (string.IsNullOrEmpty(username))
                {
                    var text = $"Username can not be empty.";
                    if (IsClientSocketConnected(client))
                    {
                        SendMessage(client, text);
                        continue;
                    }

                    else
                    {
                        break;
                    }
                }

                if (Clients.FirstOrDefault(c => c.Username == username) == null)
                {
                    client.Username = username;
                    Clients.Add(client);

                    var newMessage = new Message($"{username} joined the chat.", DateTime.Now);
                    MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                        Message = newMessage
                    });
                    BroadcastMessage(newMessage.Text);

                    try
                    {
                        foreach (var m in History.MessagesHistory)
                        {
                            var text = new StringBuilder($"{m.Username}:{m.Text}:DateTime:{m.CreatedDate}");
                            SendMessage(client, text.ToString());
                        }
                        History.AddNewMessage(newMessage);
                        break;
                    }
                    catch (SocketException e)
                    {
                        if (e.SocketErrorCode != SocketError.ConnectionAborted && e.SocketErrorCode != SocketError.ConnectionReset)
                        {
                            throw e;
                        }

                        Clients.Remove(client);
                        var message = new Message($"{client.Username} left the chat.", DateTime.Now);
                        MessageReceive?.Invoke(this, new MessageReceiveEventArgs {
                            Message = message
                        });
                        BroadcastMessage(message.Text);
                        History.AddNewMessage(message);
                    }
                }

                else
                {
                    var text = $"The username '{username}' already exists.";
                    if (IsClientSocketConnected(client))
                    {
                        SendMessage(client, text);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
Ejemplo n.º 8
0
        private void StreamRead(IAsyncResult ar)
        {
            try
            {
                int result = _stream.EndRead(ar);
                if (result > 0)
                {
                    //_log.WriteLine($"Received {result} bytes !");
                    var cmd = Command.Parse(_buffer, 0, result);
                    switch (cmd.CmdType)
                    {
                    case Command.CommandType.Ping:
                    {
                        SendCommand(new Command(Command.CommandType.Ping, new byte[] { 1 }));
                    }
                    break;

                    case Command.CommandType.GetVersion:
                        break;

                    case Command.CommandType.CreateUser:
                    {
                        int errcode = BitConverter.ToInt32(cmd.Data);
                        if (errcode == (int)CreateUserError.Success)
                        {
                            SendCommand(new Command(Command.CommandType.GetUserInfo, Encoding.UTF8.GetBytes(CurrentUser.Tag)));
                        }
                        CreateUserCallBack?.Invoke(this, new CreateUserEventArgs((CreateUserError)errcode));
                    }
                    break;

                    case Command.CommandType.Message:
                    {
                        Message msg = Message.Parse(cmd.Data);
                        MessageReceive?.Invoke(this, new MessageReceiveEventArgs(msg));
                    }
                    break;

                    case Command.CommandType.GetUserInfo:
                    {
                        User usr = User.Parse(cmd.Data);
                        if (usr.Tag == CurrentUser.Tag)
                        {
                            this.usr = usr;
                        }
                        UserInfoReceive?.Invoke(this, new UserInfoReceiveEventArgs(usr));
                    }
                    break;

                    case Command.CommandType.ChangeUserPrivacy:
                    {
                        SendCommand(new Command(Command.CommandType.GetUserInfo, Encoding.UTF8.GetBytes(CurrentUser.Tag)));
                    }
                    break;

                    case Command.CommandType.LoginUser:
                    {
                        int errcode = BitConverter.ToInt32(cmd.Data, 0);
                        if (errcode == (int)LoginUserError.Success)
                        {
                            byte[] tmp = new byte[cmd.Data.Length - 4];
                            Array.Copy(cmd.Data, 4, tmp, 0, tmp.Length);
                            User usr = User.Parse(tmp);
                            this.usr = usr;
                        }
                        LoginUserCallBack?.Invoke(this, new LoginUserEventArgs((LoginUserError)errcode));
                    }
                    break;
                    }
                }
            }
            catch (Exception ex)
            {
                _log.WriteLineError(ex);
            }
            try
            {
                if (!ar.CompletedSynchronously)
                {
                    _stream.BeginRead(_buffer, 0, _buffer.Length, StreamRead, null);
                }
            }
            catch (Exception ex)
            {
                _log.WriteLineError(ex);
            }
        }