3
\$\begingroup\$

I have a server application using TcpListener in BackgroundWorker, where my application is doing some work, and in the background listening to a IP:PORT.

The DoWork of the BackgroundWorker:

private void m_oWorker_DoWork(object sender, DoWorkEventArgs e)
{
    while (true) //infinit loop : listen
    {
        var clientSocket = _serverSocket.AcceptTcpClient();
        e.Result = clientSocket;
        m_oWorker.ReportProgress(1, clientSocket);
    }
}

At the progress change event, I do notify the form (launcher of the BackgroundWorker) that a new TcpClient is available:

The ProgressChanged of the BackgroundWorker:

private void m_oWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    _luncher.NotifyFormNewTcpClient((TcpClient)e.UserState);
    MessageBox.Show("new TcpClient Connected...");
}

Now for each form that wants to use that background worker, I need to add the method NotifyFormNewTcpClient, and in that method, I have a list of TcpListening, and I added the returned TcpClient to that list:

public void NotifyFormNewTcpClient(TcpClient tcpClient)
{
    TcpClientsList.Add(tcpClient);
    lNumberOfClient.Text = TcpClientsList.Count.ToString()  " Clients";
}

Question:

What I am doing works until now, but I wanted to know if I am doing it the right way. I want my application to keep doing some work, while it's listening in a LAN for clients that request it, and have a list of the clients (TcpClient) at any moment. Any ideas are welcome.

\$\endgroup\$
1
\$\begingroup\$

Your code looks OK, though I think there is some redundant code - e.Result = clientSocket; is never used, since work is never completed...

You might also want to consider a different approach to BackgroundWorker - TcpListener.AcceptTcpClientAsync. Instead of creating a worker thread you can do this:

private Task<TcpClient> listen() {

   return _serverSocket.AcceptTcpClientAsync().ContinueWith(clientSocket => {
       _launcher.NotifyFormNewTcpClient(clientSocket);
       MessageBox.Show("new TcpClient Connected...");
       return listen();
   });
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.