Tcp Server stops "responding"

Asked

Viewed 78 times

2

Here’s what I’ve been seeing 2 tutorial on how to do a tcp Server and a tcp Client. I had to follow all step step but for some reason when I start the server it stops responding, but when the client connecta it gives an update shows and in a textbox "New Message: Hello From Client". After that only if I connect again it will return to reply but soon after it stops responding. This only happens with the server.

 private void BtnStart_Click(object sender, EventArgs e)
    {
        TcpServerRun();
        Thread tcpserverRunThread = new Thread(new ThreadStart(TcpServerRun));

    }

    private void TcpServerRun()
    {
        TcpListener tcplistener = new TcpListener(IPAddress.Any, Convert.ToInt32(TxtBoxPort.Text));
        tcplistener.Start();
        updateUI("listening");

        while (true)
        {
            TcpClient client = tcplistener.AcceptTcpClient();
            updateUI("Connected");
            Thread tcpHandlerThread = new Thread(new ParameterizedThreadStart(tcpHandler));
            tcpHandlerThread.Start(client);
        }
    }
    private void tcpHandler(object client)
    {
        TcpClient mClient = (TcpClient)client;
        NetworkStream stream = mClient.GetStream();
        byte[] messagem = new byte[1024];
        stream.Read(messagem, 0, messagem.Length);
        updateUI("New Message: " + Encoding.ASCII.GetString(messagem));
        stream.Close();
        mClient.Close();
    }

    private void updateUI(string s)
    {
        Func<int> del = delegate()
        {
            TxtBoxLog.AppendText(s + System.Environment.NewLine);
            return 0;
        };
        Invoke(del);
    }

1 answer

2


Your server is unanswered as it is listening/waiting for a new connection. This method is called Blocking Mode of sockets.

If you need to perform some task while the server listens for a new connection there are two ways to accomplish this task:

1) Create a separate thread to listen by connections. This way the main thread is released to perform other tasks while the listening thread is stopped in "tcplistener.Accepttcpclient()".

2) There is the possibility of you programming a socket in "Non-blocking" mode, so no call the Sockets API blocks your application, but it is necessary to treat the returns to identify when there really is a connection available. It is the most used form in TCP servers, but its implementation would change a lot in relation to what is done today.

I hope I’ve been able to help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.