Я работаю на клиентском и серверном приложении tcp. Я нашел в YouTube этот код. Нет проблем с соединением с tcp клиентом и сервером, когда я отправляю сообщение, оно повторяет сообщение бесконечности, как you:you:you:you:
. Как я могу решить эту проблему? Коды использует backgroundWorker
, это может вызвать повторное сообщение. Могу ли я решить проблему, используя Thread class
?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public String TextToSend;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBoxServerIP.Text = address.ToString();
}
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBoxServerPort.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(textBoxClientIP.Text), int.Parse(textBoxClientPort.Text));
try
{
client.Connect(IpEnd);
if (client.Connected)
{
textBoxChatScreen.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 backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
try
{
recieve = STR.ReadLine();
this.textBoxChatScreen.Invoke(new MethodInvoker(delegate ()
{
textBoxChatScreen.AppendText("You:" + 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.textBoxChatScreen.Invoke(new MethodInvoker(delegate ()
{
textBoxChatScreen.AppendText("Me:" + TextToSend + "\n");
}));
}
else
{
MessageBox.Show("Sending failed");
}
backgroundWorker2.CancelAsync();
}
private void buttonSend_Click(object sender, EventArgs e)
{
if (textBoxMessage.Text != "")
{
TextToSend = textBoxMessage.Text;
backgroundWorker2.RunWorkerAsync();
}
textBoxMessage.Text = "";
}
}
}
Я попробовал код, который не могу запустить из видео на YouTube ниже.
https://www.youtube.com/watch?v=X16IyNbcAr0