Tcp Server stops responding

1

This is the following I have been watching 2 tutorial of how to do a tcp Server and a tcp Client . I had to follow everything step by step but for some reason when I start the server it stops responding, but when the client connects it from an update shows and a textbox "New Message: Hello From Client". After that only if I connect again is that he responds again but soon after he 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);
    }
    
asked by anonymous 26.08.2016 / 11:21

1 answer

2

Your server is not responding because you are listening / waiting for a new connection. This method is called sockets blocking mode.

If you need to perform some tasks while the server is listening for a new connection, there are two ways to do this:

1) Create a separate thread to listen for connections. In this way, the main thread is freed to perform other tasks while the listening thread is stopped at "tcplistener.AcceptTcpClient ()".

2) You can program a socket in "Non-Blocking" mode, so no call to the Sockets API blocks your application, but you must treat the returns to identify when a connection is actually available. It is the most used form of TCP servers, but its implementation would change a lot in relation to what is done today.

I hope I have been able to help.

    
26.08.2016 / 12:50