I am sending a string value containing some data I need in my C# application with help of a TCP Server/Client connection. The string value changes 200-300x per second.
Now, what I just want to do for now is to show the incoming strings values in a label. I've read about using a BackgroundWorker class for that case, since it would freeze the UI otherwise. But unfortunately, it doesn't work! I first tested the connection in a simple console application, there it worked perfectly. Do you may see what I'm doing wrong here?
namespace test
{
public partial class Form1 : Form
{
BackgroundWorker worker;
IPAddress ip;
Socket s;
TcpListener tcp;
public Form1()
{
InitializeComponent();
ip = IPAddress.Parse("1.2.3.4");
tcp = new TcpListener(ip, 8001);
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(TCPServer);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerCompleted);
}
string data = string.Empty;
int k = 0;
byte[] b = new byte[4096];
private void TCPServer(object sender, DoWorkEventArgs e)
{
while (true)
{
k = s.Receive(b);
data = Encoding.ASCII.GetString(b, 0, k);
e.Result = data.ToString();
}
}
private void workerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
label1.Text = e.Result.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
tcp.Start();
s = tcp.AcceptSocket();
worker.RunWorkerAsync();
}
}
}