0

This TCP Server Works, but does not process the Client disconnection I tried the TCP Client c# and Xamarin for the Android Phone\Tablet Both Connect and Send Data correctly, But the Server seems not to respond the client dis-connection The Purpose is to get a phone to control a C# Smart House app Thanks InAdvanced

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace dwkTCPServerAndroidTablet
{
    public partial class Form1 : Form
    {
        //Global Variables
        private bool isServerRunning = false;
        public Thread t = null;
        public Thread server = null;
        private const int port = 6000;// 89;
        int i = 0; // number of clients
        private TcpListener listener = null;
      //  TcpClient client = null;
       // NetworkStream stream = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void btn_StartServer_Click(object sender, EventArgs e)
        {
            i = 0;
            server = new Thread(new ThreadStart(beginserver)); //can pass data
            server.IsBackground = true; //terminated when you close your application.
            server.Start(); //starts
            isServerRunning = true;
        }

        public void beginserver()
        {
            btn_StartServer.BackColor = Color.Red;
            TcpClient newclient = new TcpClient();
            listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            //thread safe
            this.lbl_ServerStatus.Invoke(new MethodInvoker(delegate ()
            {
                lbl_ServerStatus.Text = "Server has  Started ";
            }));
            this.lbl_ClientStatus.Invoke(new MethodInvoker(delegate ()
            {
                lbl_ClientStatus.Text = "No Clients! ... ";
            }));
            //bt_Connect.Enabled = false;//grey out Connect Button
            isServerRunning = true;

            while (isServerRunning)
            {
                i++;
                newclient = listener.AcceptTcpClient();
                // client found.
                // create a thread to handle communication
                t = new Thread(new ParameterizedThreadStart(HandleClient)); //can pass data
                t.IsBackground = true; //terminated when you close your application.
                t.Start(newclient);
            }
            listener.Stop();
        }

        private void HandleClient(object newclient)
        {
            this.lbl_ClientStatus.Invoke(new MethodInvoker(delegate ()
            {
                lbl_ClientStatus.Text = "Client has Connected! ... ";
            }));
            int clientnumber = i;
            // retrieve client from parameter passed to thread
           TcpClient client = (TcpClient)newclient;

           NetworkStream stream = client.GetStream();

            byte[] bytesFrom = new byte[1024];
            
            while (client.Connected)
            {
               if(stream.DataAvailable)
                {
                    //  UnicodeEncoding ue = new UnicodeEncoding();// String => Byte  &&  Byte => String
                    byte[] stream2 = new byte[1024];
                    stream.Read(stream2, 0, stream2.Length);
                    string msg = Encoding.ASCII.GetString(stream2);
                   /// MessageBox.Show("Client sent " + msg);
                   lbl_ClientText.Text = msg;
                }
            }
///////////////////////////////////////////////////////////////
//PROBLEM
            this.lbl_ClientStatus.Invoke(new MethodInvoker(delegate ()
            {
                lbl_ClientStatus.Text = "No Clients! ... ";
            }));
            stream.Close();
            client.Close();
            t.Abort();
        }
        ////////////////////////////////////////////////////////
    }
}
dwk
  • 69
  • 1
  • 9
  • Do you have some reason to use raw TCP? Or do you just want some way to make computers talk to each other? If it is the later, there are easier ways to do it, check out something like webapi/rabbitMQ/MQTT/gRPC etc. – JonasH Mar 02 '23 at 12:39
  • Hi it's Basically a Chat app, where devices sends text code to each other It does worl well control the House – dwk Mar 02 '23 at 12:42
  • 1
    For something like a basic chat app I would really recommend some form of message queue. For example MQTT or RabbitMQ. You will likely get something that works well in much less time than trying to invent the wheel yourself. – JonasH Mar 02 '23 at 12:48

0 Answers0