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);
}