private void LoginThreadFunc(object parameters) { LoginThreadFuncParam param = (LoginThreadFuncParam)parameters; try { Dispatcher.Invoke(() => { MainChat page = new MainChat(this); selfClient.Tag = page; SelfClient.ConnectTo(new IPEndPoint(param.IPAddress, param.Port), param.BufferSize); SelfClient.Send(Encoding.UTF8.GetBytes(JsonSerializer.ConvertToText(JsonSerializer.Create(new TransPackage() { Name = NickName, PackageType = ConstDef.Login, Content = PasswordBox.Password })))); SelfClient.ReceivedMsg += page.SelfClient_ReceivedMsg; SelfClient.Disconnected += page.SelfClient_Disconnected; Program.Navigate(page); }); } catch { Dispatcher.Invoke(() => { loginWaitThread.Abort(); loginThread = null; ConnectButton.IsEnabled = true; ConnectButton.Content = "Connect"; MessageBox.Show("Communicate failed, please check your network connection.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); }); } }
public void SelfClient_ReceivedMsg(object sender, System.Net.Sockets.Socket socket, byte[] buffer, int size) { MainChat sender1 = (MainChat)((SocketClient)sender).Tag; try { string recvText = Encoding.UTF8.GetString(buffer, 0, size); JsonData[] recvJsons = JsonSerializer.ParseStream(recvText); foreach (JsonData per in recvJsons) { TransPackage recvPackage = JsonSerializer.ConvertToInstance <TransPackage>(per); sender1.DealPackage(recvPackage); } return; } catch { MessageBox.Show("Received wrong data which can't be decoded.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }