private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { while (client.Connected) { try { recieve = STR.ReadLine(); this.ChatScreenTB.Invoke(new MethodInvoker(delegate() { ChatScreenTB.AppendText(userIP.ToString() + ": " + recieve + "\n"); })); recieve = ""; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } }
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { if (client.Connected) { STW.WriteLine(TextToSend); this.ChatScreenTB.Invoke(new MethodInvoker(delegate() { OnlineTextbox.AppendText(userIP.ToString() + " is just connected.\n"); ChatScreenTB.AppendText("Me: " + TextToSend + "\n"); OnlineTextbox.Text = (userIP.ToString() + " is online now" + "\n"); })); } else { OnlineTextbox.Text = ""; MessageBox.Show("Cannot send."); } backgroundWorker2.CancelAsync(); }
private void btnClient_Click(object sender, EventArgs e) { client = new TcpClient(); IPEndPoint IPEnd = new IPEndPoint(IPAddress.Parse(ClientIPtextbox.Text), int.Parse(ClientPorttextbox.Text)); try { client.Connect(IPEnd); if (client.Connected) { OnlineTextbox.Text = (userIP.ToString() + " is online now" + "\n"); ChatScreenTB.AppendText("Connected to Server " + "\n"); STR = new StreamReader(client.GetStream()); STW = new StreamWriter(client.GetStream()); STW.AutoFlush = true; backgroundWorker1.RunWorkerAsync(); backgroundWorker2.WorkerSupportsCancellation = true; } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }