Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3431010
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T07:16:25+00:00 2026-05-18T07:16:25+00:00

I have a small method I use to disable my socket that listens for

  • 0

I have a small method I use to disable my socket that listens for incoming connections.

    /// <summary>
    /// Stops and disables the service
    /// </summary>
    public void Disable() {
        if (Running) {
            try {
                thread.Abort();
            }
            catch (System.Threading.ThreadAbortException) {
                // This catch is not raised.
                // We can simply process our closing of the socket and nullify the thread
            }
            finally {
                socket.Close();
                socket = null;
                thread = null;
                if (socket == null && thread == null) {
                    m_Running = false;
                    OnDisabled(this, new EventArgs());
                }
            }
        }
    }

My problem is that even after I call Close() and nullify the socket, the clients still remain connected. I ran a check using netstat -a, and it shows the clients are still connected.

TCP    127.0.0.1:2161         activate:7777          ESTABLISHED
TCP    127.0.0.1:7777         activate:2161          ESTABLISHED

7777 is the port my host socket listens on. So my question is, after closing the host socket, why do the client sockets not disconnect. How do they remain connected to a socket that is null, and is no longer listenning?

Some additional info

    /// <summary>
    /// Enables and runs the service
    /// </summary>
    public void Enable() {
        if (!Running) {
            ThreadStart start = new ThreadStart(RunServiceAsync);
            thread = new Thread(start);
            thread.IsBackground = true;
            thread.Start();
            m_Running = true;
            OnEnabled(this, new EventArgs());
        }
    }

The above method is how the thread is created. Everything works fine, the threading, connections; the only issue is when I close the socket (host), and nullify it the clients are still connected to it.

The question is, once the host socket is closed and set to null, what are the clients connected to? Shouldn’t they disconnect and lose connection to the host, because the host socket is closed?

Here is the full code to help

// *********************************************************************

// [DCOM Productions]
// [Copyright (C) DCOM Productions All rights reserved.]
// ***************************************

namespace CipherBox.Drivers {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.ComponentModel;
using CipherBox.Objects;

/// <summary>
/// Driver that manages the network connection between the master program and clients, also provides informational events
/// </summary>
public class NetworkDriver : IDriver {

    #region Fields

    private Socket socket;
    private Thread thread;

    #endregion

    #region Properties

    private int m_Port = 7777;
    /// <summary>
    /// Gets the port that the network runs on. The default port is 7777. 
    /// </summary>
    public int Port {
        get {
            return m_Port;
        }
    }

    #endregion

    #region Events

    /// <summary>
    /// Delegate for when a node connects to the service
    /// </summary>
    public delegate void NodeConnectedEventHandler(object sender, NetworkNodeEventArgs e);
    /// <summary>
    /// Triggers when an node connects to the service
    /// </summary>
    public event NodeConnectedEventHandler NodeConnected;
    /// <summary>
    /// Event callback for NodeConnected
    /// </summary>
    private void OnNodeConnected(object sender, NetworkNodeEventArgs e) {
        if (NodeConnected != null) {
            foreach (NodeConnectedEventHandler handler in NodeConnected.GetInvocationList()) {
                ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                if (syncInvoke != null && syncInvoke.InvokeRequired) {
                    syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                }
                else {
                    NodeConnected(this, e);
                }
            }
        }
    }

    /// <summary>
    /// Delegate for when a node disconnects from the service
    /// </summary>
    public delegate void NodeDisconnectedEventHandler(object sender, NetworkNodeEventArgs e);
    /// <summary>
    /// Triggers when an node disconnects from the service
    /// </summary>
    public event NodeDisconnectedEventHandler NodeDisconnected;
    /// <summary>
    /// Event callback for NodeDisconnected
    /// </summary>
    private void OnNodeDisconnected(object sender, NetworkNodeEventArgs e) {
        if (NodeDisconnected != null) {
            foreach (NodeDisconnectedEventHandler handler in NodeDisconnected.GetInvocationList()) {
                ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                if (syncInvoke != null && syncInvoke.InvokeRequired) {
                    syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                }
                else {
                    NodeDisconnected(this, e);
                }
            }
        }
    }

    #endregion

    #region Methods

    private NetworkNode FillNode(Socket socket) {
        StringBuilder stream = new StringBuilder();
        byte[] buffer = new byte[4096];
        int bytesReceived = -1;
        do {
            try {
                bytesReceived = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
            }
            catch (System.Net.Sockets.SocketException) {
                return null;
            }
            finally {
                stream.Append(Encoding.ASCII.GetString(buffer, 0, bytesReceived));
            }
        } while (!stream.ToString().EndsWith("\r\n\r\n"));
        string[] packet = stream.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None);
        if (packet.Length == 9) {
            if (packet[0].ToLower() == "CipherBox".ToLower()) {
                NetworkNode node = new NetworkNode();
                node.Domain = packet[1];
                node.LocalIP = IPAddress.Parse(packet[2]);
                node.MachineName = packet[3];
                node.Platform = packet[4];
                node.RemoteIP = IPAddress.Parse(packet[5]);
                node.Workgroup = packet[6];
                node.Socket = socket;
                return node;
            }
            else {
                return null;
            }
        }
        else {
            return null;
        }
    }

    private bool IsDisconnected(Socket socket) {
        bool connected = false;
        try {
            connected = !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
        }
        catch (System.Net.Sockets.SocketException) {
            connected = false;
        }
        return !connected;
    }

    private void MonitorNode(NetworkNode node) {
        ParameterizedThreadStart start = new ParameterizedThreadStart(MonitorNodeAsync);
        Thread thread = new Thread(start);
        thread.IsBackground = true;
        thread.Start(node);
    }

    private void MonitorNodeAsync(object obj) {
        NetworkNode node = obj as NetworkNode;
        while (Running || node != null) {
            if (IsDisconnected(node.Socket)) {
                node.Socket.Shutdown(SocketShutdown.Both);
                node.Socket.Close();
                node.Socket = null;
                OnNodeDisconnected(null, new NetworkNodeEventArgs(node));
                return;
            }
            else {
                Thread.Sleep(1000);
            }
        }
    }

    private void RunServiceAsync() {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEP = new IPEndPoint(IPAddress.Any, Port);
        socket.Bind(localEP);
        socket.Listen(1);
        do {
            Socket client;
            try {
                client = socket.Accept();
            }
            catch (System.Net.Sockets.SocketException) {
                continue;
            }
            NetworkNode node = FillNode(client);
            if (node != null) {
                OnNodeConnected(null, new NetworkNodeEventArgs(node));
                MonitorNode(node);
            }
        } while (Running);
    }

    /// <summary>
    /// Sets the port that the network runs on
    /// </summary>
    /// <param name="port">The port to set</param>
    public void SetPort(int port) {
        m_Port = port;
    }

    #endregion

    #region IDriver Members

    /// <summary>
    /// Triggered when the network driver is disabled
    /// </summary>
    public event EventHandler<EventArgs>  Disabled;
    /// <summary>
    /// Event callback for Disabled
    /// </summary>
    private void OnDisabled(object sender, System.EventArgs e) {
        if (Disabled != null) {
            foreach (EventHandler<EventArgs> handler in Disabled.GetInvocationList()) {
                ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                if (syncInvoke != null && syncInvoke.InvokeRequired) {
                    syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                }
                else {
                    Disabled(this, e);
                }
            }
        }
    }

    /// <summary>
    /// Triggered when the network driver is enabled
    /// </summary>
    public event EventHandler<EventArgs>  Enabled;
    /// <summary>
    /// Event callback for Enabled
    /// </summary>
    private void OnEnabled(object sender, System.EventArgs e) {
        if (Enabled != null) {
            foreach (EventHandler<EventArgs> handler in Enabled.GetInvocationList()) {
                ISynchronizeInvoke syncInvoke = handler.Target as ISynchronizeInvoke;
                if (syncInvoke != null && syncInvoke.InvokeRequired) {
                    syncInvoke.Invoke(handler, new object[] { handler.Target, e });
                }
                else {
                    Enabled(this, e);
                }
            }
        }
    }

    /// <summary>
    /// Stops and disables the service
    /// </summary>
    public void Disable() {
        if (Running) {
            try {
                thread.Abort();
            }
            catch (System.Threading.ThreadAbortException) {
                // This catch is not raised.
                // We can simply process our closing of the socket and nullify the thread
            }
            finally {
                socket.Close();
                socket = null;
                thread = null;
                if (socket == null && thread == null) {
                    m_Running = false;
                    OnDisabled(this, new EventArgs());
                }
            }
        }
    }

    /// <summary>
    /// Enables and runs the service
    /// </summary>
    public void Enable() {
        if (!Running) {
            ThreadStart start = new ThreadStart(RunServiceAsync);
            thread = new Thread(start);
            thread.IsBackground = true;
            thread.Start();
            m_Running = true;
            OnEnabled(this, new EventArgs());
        }
    }

    private bool m_Running = false;
    /// <summary>
    /// Gets a System.Boolean value indicating whether the service is running or not
    /// </summary>
    public bool Running {
        get {
            return m_Running;
        }
    }

    #endregion
}

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T07:16:25+00:00Added an answer on May 18, 2026 at 7:16 am

    Yo have to call socket.shutdown(Both) the parameter could be Send, Receive or Both Depending of how you like to end the connection. This function send the necessary TCP message to the client to close the connection.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a small utility that I use to download an MP3 file from
I have a small JS function that does Ajax for me and another like
I have a small VB.NET application that I'm working on using the full version
I have a small application I am working on that at one point needs
I have small page which has label, DropDownList and a submit button. <div> <asp:label
I have small problem with my .net 2.0 winforms application. I want to embed
Where I work, we have small teams of 2 - 5 people. As a
I have a small local network. Only one of the machines is available to
I have a small diagnostic VB.Net application ( 2 forms, 20 subs & functions)
We have a small embedded system without any video or serial ports (i.e. we

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.