Click here to Skip to main content
15,063,393 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I have a server which is running on a port and is waiting for connections.
The connect part is working fine but when i click on "Disconnect" button, it is actually disconnecting.
Here is the part of my code
C#
private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (btnDisconnect.Enabled == true)
            {
                btnDisconnect.BackColor = System.Drawing.Color.DarkBlue;
                btnDisconnect.ForeColor = System.Drawing.Color.AntiqueWhite;
                Listener l = new Listener(ipAddr); 
                try
                {
                    
                    txtLog.AppendText("Stopping listener");
                    l.disConnect();
                    txtLog.AppendText("stopped");
                }
                catch (Exception)
                {
                    txtLog.AppendText("Unhandled Listener Close");
                }
            }
        }


Here is the listener class
C#
class Listener
    {
        private IPAddress ipAddress;
        private TcpClient tcpClient;
        private TcpListener tcpListener;
        private Thread thrListener;
        bool ServRunning = false;
        // The event and its argument will notify the form when a user has connected, disconnected, send message, etc.
        public static event StatusChangedEventHandler StatusChanged;
        private static StatusChangedEventArgs e;
        public Listener(IPAddress address)
        {
            ipAddress = address;
        }
        public static void OnStatusChanged(StatusChangedEventArgs e)
        {
            StatusChangedEventHandler statusHandler = StatusChanged;
            if (statusHandler != null)
            {
                // Invoke the delegate
                statusHandler(null, e);
            }
        }
        public void startListening()
        {

            // Get the IP of the first network device, however this can prove unreliable on certain configurations
            IPAddress ipaLocal = ipAddress;

            // Create the TCP listener object using the IP of the server and the specified port
            tcpListener = new TcpListener(ipaLocal, 13);

            // Start the TCP listener and listen for connections
            tcpListener.Start();

            // The while loop will check for true in this before checking for connections
            ServRunning = true;

            // Start the new tread that hosts the listener
            thrListener = new Thread(KeepListening);
            thrListener.Start();
        }

        private void KeepListening()
        {
            // While the server is running
            while (ServRunning == true)
            {
                // Accept a pending connection
                tcpClient = tcpListener.AcceptTcpClient();
                e = new StatusChangedEventArgs("Connected");
                OnStatusChanged(e);
                bool m = true;
                while (m)
                {
                    byte[] bytes = new byte[2560];
                    NetworkStream stream = tcpClient.GetStream();
                    stream.Read(bytes, 0, bytes.Length);
                    string mstrMessage = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
                    //MessageBox.Show(mstrMessage);
                    e = new StatusChangedEventArgs(mstrMessage);
                    OnStatusChanged(e);
                    //SocketHelper helper = new SocketHelper();
                    //helper.processMsg(tcpClient, stream, bytes);
                    XmlDocument myxmlDoc = new XmlDocument();
                    myxmlDoc.LoadXml(mstrMessage);
                    string message = myxmlDoc.SelectSingleNode("Connect/@message").InnerText;
                    message = Regex.Replace(message, @"\t|\n|\r", "");
                    //MessageBox.Show(message);
                    if (message.Equals("send"))
                    {
                        DriveInfo1 d = new DriveInfo1();
                        string mstrDriveResponse = d.getDrive();
                        byte[]  bytesSent = Encoding.ASCII.GetBytes(mstrDriveResponse);
                        stream.Write(bytesSent, 0, bytesSent.Length);
                        //MessageBox.Show("Received Drive data \n" + mstrDriveResponse);
                        string mstrBuildResponse = d.Installed();
                        byte[] byteSent = Encoding.ASCII.GetBytes(mstrBuildResponse);
                        stream.Write(byteSent, 0, byteSent.Length);
                        //MessageBox.Show("Received Build data \n" + mstrBuildResponse);
                    }
                    else
                    {
                        string mstrResponse = @"<?xml version=""1.0"" encoding=""utf-8""?><Response message=""Unable to parse xml"">";
                        byte[] bytesSent = Encoding.ASCII.GetBytes(mstrResponse);
                        stream.Write(bytesSent, 0, bytesSent.Length);
                    }
                    m = false;
                    stream.Close();
                }
            }
        }
        public void disConnect()
        {
            tcpClient.Close();
            tcpListener.Stop();
        }
    }


Please help to rectify the error!!
Thanks :)
Posted
Comments
DamithSL 20-May-14 6:21am
   
what is the error?
sovit agarwal 20-May-14 6:26am
   
NullReferenceException-Object reference not set to an instance of an object.
and it is pointing to tcpClient.GetStream().Close();
sovit agarwal 20-May-14 6:27am
   
I guess its happening because one object of listener class is creating the connection while another object of the same class is trying to disconnect what it has not initiated.

1 solution

include below code
C#
public void disConnect()
{
    if(tcpClient !=null)
    {
        tcpClient.GetStream().Close();
        tcpClient.Close();
        tcpListener.Stop();
    }
}


read this KB for more information :
The TcpClient Close method does not close the underlying TCP connection[^]
   
v2
Comments
sovit agarwal 20-May-14 6:14am
   
This doesn't seem to be working in my case

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900