private void ConnectButton_Click(object sender, EventArgs e) { ChattextBox.Text = ""; client = new TcpClient(); IPHostEntry host; host = Dns.GetHostEntry(textBoxHostname.Text); IPEndPoint IpEnd = new IPEndPoint(host.AddressList[0], int.Parse("10006")); try { client.Connect(IpEnd); if (client.Connected) { ChattextBox.AppendText("Connected to server" + "\n"); STW = new StreamWriter(client.GetStream()); STR = new StreamReader(client.GetStream()); STW.AutoFlush = true; backgroundWorker1.RunWorkerAsync(); backgroundWorker2.WorkerSupportsCancellation = true; } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { if (client.Connected) { STW.WriteLine(TextToSend); this.ChattextBox.Invoke(new MethodInvoker(delegate() { ChattextBox.AppendText("Client:" + TextToSend + "\n"); })); } else { MessageBox.Show("Sending failed"); } backgroundWorker2.CancelAsync(); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { while (client.Connected) { try { receive = STR.ReadLine(); this.ChattextBox.Invoke(new MethodInvoker(delegate() { ChattextBox.AppendText("Server:" + receive + "\n"); })); receive = ""; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } }