コード例 #1
0
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Visibility = Visibility.Hidden;
            SetInfo("请认证用户信息");
            LoadUserSetting();
            if (!user.AutoSign)
            {
                CheckVersion();
            }
            bool result = (bool)new UserAccount().ShowDialog();

            if (result)
            {
                SaveUserSetting();
                SetInfo("");
                FrameTrigger          = new DispatcherTimer();
                FrameTrigger.Tick    += new EventHandler(ScrollMessageItemList);
                FrameTrigger.Interval = new TimeSpan(0, 0, 0, 0, 10);
                FrameTrigger.Start();
                popup.Show();
                popup.Owner = this;
                if (user.DisablePopupMessage)
                {
                    popup.Visibility = Visibility.Hidden;
                }
                MessageReceiver = MessageReceive.GetInstance(GetMessageCount());
                StartMessageReceive();
                StartCheckVersion();
                isWorking  = true;
                Visibility = Visibility.Visible;
            }
        }
コード例 #2
0
ファイル: ChatClient.cs プロジェクト: ViktoriyaKaleda/TcpChat
        /// <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);
        }
コード例 #3
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)
                });
            }
        }
コード例 #4
0
 /// <summary>
 /// 初始化一个<see cref="MessageReceiveOutputDto"/>类型的新实例
 /// </summary>
 public MessageReceiveOutputDto(MessageReceive entity)
 {
     Id            = entity.Id;
     ReadDate      = entity.ReadDate;
     NewReplyCount = entity.NewReplyCount;
     MessageId     = entity.MessageId;
     UserId        = entity.UserId;
     CreatedTime   = entity.CreatedTime;
 }
コード例 #5
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);
        }
コード例 #6
0
ファイル: ChatClient.cs プロジェクト: ViktoriyaKaleda/TcpChat
 /// <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;
         }
     }
 }
コード例 #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            _changeState = MessageReceive.Instance;
            string name = Request.Form["name"]; //在系统中配置的接收用户名
            string pwd  = Request.Form["pwd"];  //在系统中配置的接收密码
            string args = Request.Form["args"]; //上行数据,根据文档4.1格式解析

            if (args.Contains("#@@#"))          //多条上行一起推送过来的
            {
                MessageModel mm    = new MessageModel();
                string[]     allmo = args.Split(new string[] { "#@@#" }, StringSplitOptions.RemoveEmptyEntries);//拆分成一条一条的信息,放到数组中
                for (int i = 0; i < allmo.Length; i++)
                {
                    string[] mo = allmo[i].Split(new string[] { "#@#" }, StringSplitOptions.None);//这个地方要用None,空值不能移除
                    mm.Phone         = mo[0];
                    mm.ReplayContext = mo[1];
                    mm.ReplayDate    = DateTime.Parse(mo[2]);
                    //mo[3]  系统扩展码+发送时带的extno值  一般情况下账号的特服号即为系统扩展码。 如账号的特服号是 1001,发送时带的extno=888, mo[3]=1001888

                    db.Messages.Add(mm);
                    db.SaveChanges();
                    _changeState.BoardMessage(mm.Phone, mm.ReplayContext);
                }
            }
            else//只有一条上行信息
            {
                MessageModel mm = new MessageModel();
                string[]     mo = args.Split(new string[] { "#@#" }, StringSplitOptions.None);//这个地方要用None,空值不能移除
                mm.Phone         = mo[0];
                mm.ReplayContext = mo[1];
                mm.ReplayDate    = DateTime.Parse(mo[2]);
                //mo[3]  系统扩展码+发送时带的extno值  一般情况下账号的特服号即为系统扩展码。 如账号的特服号是 1001,发送时带的extno=888, mo[3]=1001888

                db.Messages.Add(mm);
                db.SaveChanges();
                _changeState.BoardMessage(mm.Phone, mm.ReplayContext);
            }
        }
コード例 #8
0
ファイル: ChatServer.cs プロジェクト: ViktoriyaKaleda/TcpChat
        /// <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;
                }
            }
        }
コード例 #9
0
 protected void recieve(object sender, EventArgs e)
 {
     MessageReceive?.Invoke(sender, e);
 }
コード例 #10
0
ファイル: ChatServer.cs プロジェクト: ViktoriyaKaleda/TcpChat
        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;
                    }
                }
            }
        }
コード例 #11
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);
            }
        }
コード例 #12
0
 private void OnMessageReceive(object sender, MessageReceive message)
 {
     MessageManager.Instance.MessageReceive();
 }