Reputation: 87
I have a BackGroundWorker that i use to listen in a port
It works pretty well, the problems is that after the first receiving it stops working, i tried with a "while(true)" and restarting it in the RunWorkerComplete event but had no success
With stopPoints i can see that it does a console.writeline() with the correct message, then it stops working
using System.Net.Sockets;
class Program
{
private static BackgroundWorker worker = new BackgroundWorker();
static void Main(string[] args)
{
Program P = new Program();
P.notifyIcon1.Visible = true;
P.ipaddress = IPAddress.Any;
P.tcpServer = new TcpServer(P.ipaddress.ToString(), 3001);
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
//worker.ProgressChanged += worker_ProgressChanged;
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
if (!worker.IsBusy) worker.RunWorkerAsync();
Console.WriteLine("Press ENTER to exit the server.");
Console.ReadLine();
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
IPEndPoint endPoint;
Socket tcpClient;
Socket listener;
int pendingConnectionQueueSize;
IPAddress ipaddress = IPAddress.Any;
endPoint = new IPEndPoint(ipaddress, 3001);
pendingConnectionQueueSize = 100;
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);
listener.Listen(pendingConnectionQueueSize);
Console.WriteLine("conn..");
byte[] receiveBuffer = new byte[4096];
tcpClient = listener.Accept();
tcpClient.RemoteEndPoint.ToString();
while (true)
{
int rc = tcpClient.Receive(receiveBuffer);
string msg = Encoding.ASCII.GetString(receiveBuffer);
if (rc == 0)
break;
Console.WriteLine(msg.Trim());
}
listener.Close();
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (!worker.IsBusy) worker.RunWorkerAsync();//restart
}
}
Upvotes: 2
Views: 380
Reputation: 1062494
then it stops working
The code shown works, and reads as many times as data is available; I tested it with telnet, and it worked fine (ish - there are still some bugs around the ASCII decode of the buffer, as discussed in comments)!
If it is only reading once, then I can only assume that your client isn't sending more data on the same connection. The code shown only accepts one connection, and then reads it to the end.
Upvotes: 2