Using TcpListener.AcceptSocket(); in a separate thread causes the thread to block?

萝らか妹 提交于 2019-12-02 04:27:24

问题


I have tried to work around this as well as debug but I'm at a loose end here :( is there any alternative to using this to check for a client connection? This code works fine in a console application so i am guessing the thread is being blocked, although it may be something else i can't see?

public partial class Form1 : Form
{
    Socket s;

Declatation of socket.

private void startButton_Click(object sender, EventArgs e)
    {
        checkTimer.Enabled = true;
        if (bw.IsBusy != true)
        {
            bw.RunWorkerAsync();
        }
    }

Background thread to start on button press.

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
        BackgroundWorker worker = sender as BackgroundWorker;

        working();
}

Thread runs the "working" method.

 private void working()
 {
     if (threadFirstRun == true)
     {
            threadFirstRun = false;
     }

        try
        {

            String tempAddr = tbAddr.Text;
            IPAddress ipAd = IPAddress.Parse("147.197.204.172");
            // use local m/c IP address, and 
            // use the same in the client
            String tempPort = tbPort.Text;
            /* Initializes the Listener */
            TcpListener myList = new TcpListener(ipAd, 3000);

            /* Start Listeneting at the specified port */
            myList.Start();
            tcConnection1 = "Console:\n" + "The server is running at port 3000...";
            tcConnection2 = "\n" + "The local End point is  :" + myList.LocalEndpoint;
            tcConnection3 = "\n" + "Waiting for a connection.....";

            while (true)
            {
                s = myList.AcceptSocket();
                if (s != null)
                {
                    if (connectionEstab == false)
                    {
                        tcEstab = "\n" + "Connection accepted from " + s.RemoteEndPoint;
                        connectionEstab = true;
                    }


                    byte[] b = new byte[100];
                    int k = s.Receive(b);
                    //Console.WriteLine("Recieved...");
                    for (int i = 0; i < k; i++)
                    {
                        //Console.Write(Convert.ToChar(b[i]));
                        tcValue = tcValue + Convert.ToString(b[i]);
                        valueArray[ii] = (float)Convert.ToDouble(b[i]);
                    }
                    tcValue = tcValue + "\n";
                    ii++;
                }
                else
                {
                    Thread.Sleep(200);
                }
            }

            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            rtbConsole.Text = rtbConsole.Text + "\n" + "Sent Acknowledgement";
            /* clean up */
            s.Close();
            myList.Stop();
        }
        catch (Exception ex)
        {
            tcError = "\n\n" + "Error..... " + ex.StackTrace;
        }
}

Working method starts the server and blocks upon calling myList.AcceptSocket();?

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
        if ((e.Cancelled == true))
        {
            rtbConsole.Text = rtbConsole.Text + "\n" + "Canceled!";
        }

        else if (!(e.Error == null))
        {
            rtbConsole.Text = rtbConsole.Text + "\n\n" + ("Error: " + e.Error.Message);
        }

        else
        {
            rtbConsole.Text = rtbConsole.Text + "\n" + "Done!";
        }
}

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
        rtbConsole.Text = rtbConsole.Text + "\n" + (e.ProgressPercentage.ToString() + "%");
}

private void stopButton_Click(object sender, EventArgs e)
{
        checkTimer.Enabled = false;
        if (bw.WorkerSupportsCancellation == true)
        {
            bw.CancelAsync();
        }
}

Other methods for some completeness.

EDIT AS I SUCK AT EXPLAINING MY PROBLEMS :(

Sending data from my android device is received by a console app running 1 thread, however nothing seems to happen in this windows form application upon sending data to the same ip and port from the same program on the same device. The separate thread just stays blocked and the android app cannot complete communication to send the data.


回答1:


It is supposed to block. From MSDN:

AcceptSocket is a blocking method that returns a Socket that you can use to send and receive data. If you want to avoid blocking, use the Pending method to determine if connection requests are available in the incoming connection queue.

You can turn your whole implementation to use the async version: AcceptSocketAsync. Note this wont block your method, it will yield control back to the caller until a new Socket has been connected.

private async void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    await WorkingAsync();
}

And inside WorkingAsync:

private Task WorkingAsync
{
    // Do all other stuff,

    Socket socket = await myList.AcceptSocketAsync();

   // Do rest of stuff with the socket
}

I recommend you like at What is the async/await equivalent of a ThreadPool server? for a full implementation of an async tcp connection handler




回答2:


It's supposed to block. It can never return null. (Why is everybody doing this? It's like nobody on the web uses Accept correctly.)

Your problem is that after accepting one connection you process that connection and do nothing to resume accepting. The standard pattern is:

while (true) {
 var connectionSocket = listeningSocket.Accept();
 ProcessAsynchronously(connectionSocket);
}

Make sure ProcessAsynchronously returns immediately. Start a new Task or use async/await.

As you never exit the while loop you never get to sending data. Move all processing logic into ProcessAsynchronously.



来源:https://stackoverflow.com/questions/24680562/using-tcplistener-acceptsocket-in-a-separate-thread-causes-the-thread-to-bloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!