-1

I am having a hard time. I am new to this. Can someone help me with this. Every time I call the _clientSocket.Close(); I got an error message.

Cannot access a disposed object. Object name: System.net.Sockets.Socket

There's no error in my code. It can run smooth but every time I open and close a form it comes up. I want to get rid of it. The program can run with it but its to irritating. Because when I try to open a client it will pop up. And when the time of the client is done, the form will close and the login will come out with another pop up of

Cannot access a disposed object. Object name: System.net.Sockets.Socket

I use _clientSocket.Close() because if I'm not closing the sockets it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.

I'm doing this for my project and I'm just studying myself so some of the comments I really don't understand but I'm trying my best to learn from it thank you!

Your suggestions will much appreciated. Correct me if I'm wrong thank you!

This code is the Loginform when Server sends -O it will _clientSocket.Close(); and open the Form2. If Form2 use all the time it will back to Loginform and form2 _clientSocket.Close(); I call the _clientSocket.Close(); because the Server Checklistbox that catches all the connected sockets will be doubled if I don't close the Sockets.

Edited

Server

namespace RealVersion2
{
        public partial class Server : Form
        {
            public class SocketT2h
            {
                public Socket _Socket { get; set; }
                public string _Name { get; set; }
                public SocketT2h(Socket socket)
                {
                    this._Socket = socket;
                }
            }
            private byte[] _buffer = new byte[1024];
            public List<SocketT2h> __ClientSockets { get; set; }
            List<string> _names = new List<string>();
            private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            public Server()
            {
                InitializeComponent();
                CheckForIllegalCrossThreadCalls = false;
                __ClientSockets = new List<SocketT2h>();
                this.list_Client.SelectionMode = System.Windows.Forms.SelectionMode.None;
            }


            private void Send_Click(object sender, EventArgs e)
            {
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " );
                            }
                            else
                            {

                                Sendata(__ClientSockets[j]._Socket, "Server: " + txt_Text.Text);
                            }

                        }
                    }
                    rich_Text.AppendText("\nServer: " + txt_Text.Text);
                    txt_Text.Text = "";
                }
            }
                    void Sendata(Socket socket, string noidung)
            {
                byte[] data = Encoding.ASCII.GetBytes(noidung);
                socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                _serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
            }
            private void SendCallback(IAsyncResult AR)
            {
                Socket socket = (Socket)AR.AsyncState;
                socket.EndSend(AR);
            }
            private void SetupServer()
            {
                try
                {
                    lb_stt.Text = "Setting up server . . .";
                    _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8000));
                    _serverSocket.Listen(1);
                    _serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            private void AppceptCallback(IAsyncResult ar)
            {
                Socket socket = _serverSocket.EndAccept(ar);
                __ClientSockets.Add(new SocketT2h(socket));
                list_Client.Items.Add(socket.RemoteEndPoint.ToString());

                lb_soluong.Text = "Number of clients connected: " + __ClientSockets.Count.ToString();
                lb_stt.Text = "Client connected. . .";
                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                _serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
            }

            private void ReceiveCallback(IAsyncResult ar)
            {

                           Socket socket = (Socket)ar.AsyncState;
                if (socket.Connected)
                {
                    int received;
                    try
                    {
                        received = socket.EndReceive(ar);
                    }
                    catch (Exception)
                    {
                        // client close connection
                        for (int i = 0; i < __ClientSockets.Count; i++)
                        {
                            if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
                            {
                                //taga tapoon ng panget
                                list_Client.Items.RemoveAt(i);
                                __ClientSockets.RemoveAt(i);
                                lb_soluong.Text = "Number of clients connected: "+__ClientSockets.Count.ToString();
                            }

                        }
                        //delete in list
                        return;
                    }
                    if (received!=0)
                    {
                        byte[] dataBuf = new byte[received];
                        Array.Copy(_buffer, dataBuf, received);
                        string text = Encoding.ASCII.GetString(dataBuf);
                        //lb_stt.Text = "Text received: " + text;

                        string reponse = string.Empty;
                        //reponse = "Server: Hi! You're Connected to the Librarian.";

                            if (text.Contains("@@"))
                        {
                            for (int i = 0; i < list_Client.Items.Count; i++)
                            {
                                if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
                                {
                                    list_Client.Items.RemoveAt(i);
                                    list_Client.Items.Insert(i, text.Substring(1, text.Length - 1));
                                    __ClientSockets[i]._Name = text;
                                    socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                                    return;
                                }

                            }
                        }


                        for (int i = 0; i < __ClientSockets.Count; i++)
                        {
                            if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
                            {   
                                rich_Text.AppendText("\n" + __ClientSockets[i]._Name + ": " + text);
                            }
                        }

                    }
                    else
                    {
                        for (int i = 0; i < __ClientSockets.Count; )
                        {
                            if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
                            {
                                __ClientSockets.RemoveAt(i);
                                lb_soluong.Text ="The number of clients connected: " + __ClientSockets.Count.ToString();
                            }
                        }
                    }
                }
                    socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
            }


            private void tabPage1_Click(object sender, EventArgs e)
            {

            }

            private void Server_Load(object sender, EventArgs e)
            {
                SetupServer();
            }




            private void Restartbtn_Click(object sender, EventArgs e)
            {
                string Restart = string.Empty;
                Restart = "-r";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Restart);
                            }
                        }
                    }
                    rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
            }

            private void Shutdownbtn_Click(object sender, EventArgs e)
            {
                string Shutdown = string.Empty;
                Shutdown = "-s";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Shutdown);
                            }
                        }
                    }
                    rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
            }



            private void list_Client_SelectedIndexChanged(object sender, EventArgs e)
            {
                for (int i = 0; i < list_Client.Items.Count; i++)
                {


                    if (list_Client.GetItemRectangle(i).Contains(list_Client.PointToClient(MousePosition)))
                    {
                        switch (list_Client.GetItemCheckState(i))
                        {
                            case CheckState.Checked:
                                list_Client.SetItemCheckState(i, CheckState.Unchecked);
                                break;
                            case CheckState.Indeterminate:
                            case CheckState.Unchecked:
                                list_Client.SetItemCheckState(i, CheckState.Checked);
                                break;
                        }

                    }

                }
            }



            private void openPCToolStripMenuItem_Click_1(object sender, EventArgs e)
            {
                string Open = string.Empty;
                Open = "-O";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Open);
                                //use [i] if u dont want name in list
                            }
                        }
                    }
                    //rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
                }



            private void Server_FormClosing(object sender, FormClosingEventArgs e)
            {
                string Ext = string.Empty;
                Ext = "exit";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
                            }
                        }
                    }
                    //rich_Text.AppendText("\nServer: " + txt_Text.Text);
                    Application.Exit();
                    _serverSocket.Close();
                }
            }

            private void End_Click(object sender, EventArgs e)
            {
                string Ext = string.Empty;
                Ext = "close";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
                            }
                        }
                    }
                    //rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
            }


        }
    }

Client

public partial class UserLog : Form
{


    private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    TimeSpan countdownClock = TimeSpan.Zero;

    public UserLog()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string Username = "User";
        string Pass = "123";

        if (Username == textBox1.Text && Pass == textBox2.Text)

        {
            MessageBox.Show("Login Successfully");
            Usertimer User = new Usertimer(textBox1.Text);
            User.Show();
            this.Hide();
            _clientSocket.Dispose();
            _clientSocket.Close();



        }
        else
        {
            MessageBox.Show("Please Enter valid Username or Password");
        }
    }


    byte[] receivedBuf = new byte[1024];
    protected override void OnClosing(CancelEventArgs e)
    {
        base.OnClosing(e);
        if (_clientSocket != null && _clientSocket.Connected)
        {
            _clientSocket.Close();
        }
    }

    private void ReceiveData(IAsyncResult ar)
    {

        try
        {
            int received = _clientSocket.EndReceive(ar);
            if (received == 0)
            {
                return;
            }

            Array.Resize(ref receivedBuf, received);
            string text = Encoding.Default.GetString(receivedBuf);
            Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
            AppendtoTextBox(text);

            if (text == "Server: -O")
            {

                Thread NT = new Thread(() =>
                {
                    this.BeginInvoke((Action)delegate ()
                    {


                         textBox1.Text = "Guest";
                         this.Hide();
                        _clientSocket.Close();
                        Usertimer us = new Usertimer(textBox1.Text);
                us.Show();


                    });

                });
                NT.Start(); 

            }
            if (text == "Server: exit")
            {
                _clientSocket.Close();
                Application.Exit();

            }

            _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);

        }

        catch (ObjectDisposedException ex)
        {
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

    private void AppendtoTextBox(string text)
    {
        MethodInvoker invoker = new MethodInvoker(delegate
        {
            textBox4.Text += text + "\r\n";

        });
        this.Invoke(invoker);
    }
    private void LoopConnect()
    {
        int attempts = 0;
        while (!_clientSocket.Connected)
        {
            try
            {
                attempts++;
                _clientSocket.Connect(IPAddress.Parse(textBox5.Text), 8000);
                //_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 100);

            }
            catch (SocketException)
            {
                //Console.Clear();
                lb_stt.Text = ("Connection attempts: " + attempts.ToString());
            }
        }
        AppendtoTextBox(reponse);
    }


    private void button2_Click(object sender, EventArgs e)
    {
        LoopConnect();
        // SendLoop();
        _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
        byte[] buffer = Encoding.ASCII.GetBytes("@@"+txName.Text);
        _clientSocket.Send(buffer);
    }

    private void UserLog_Load(object sender, EventArgs e)
    {
        LoopConnect();
        _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
        byte[] buffer = Encoding.ASCII.GetBytes("@@"+txName.Text);
        _clientSocket.Send(buffer);
    }

    private void UserLog_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }
}

}

Form2 of the client

    public partial class Usertimer : Form
    {
        private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);



        public Usertimer(string pass)
        {
            InitializeComponent();
            label3.Text = pass;


        }

        byte[] receivedBuf = new byte[1024];
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            this.btnConnect_Click(null, null);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            if (_clientSocket != null && _clientSocket.Connected)
            {
                _clientSocket.Close();
            }
        }
        private void ReceiveData(IAsyncResult ar)
        {
            try
            {
                int received = _clientSocket.EndReceive(ar);
                if (received == 0)
                {
                    return;
                }

                Array.Resize(ref receivedBuf, received);

                string text = Encoding.Default.GetString(receivedBuf);


                if (text == "Server: close")
                {
                    Thread NT = new Thread(() =>
                    {
                        this.BeginInvoke((Action)delegate ()
                        {

                            UserLog Log = new UserLog();
                            Log.Show();
                            this.Close();
                            _clientSocket.Close();

                        });

                    });
                    NT.Start();

                }

                Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
                AppendtoTextBox(text);
                _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AppendtoTextBox(string text)
        {
            MethodInvoker invoker = new MethodInvoker(delegate
            {
                richTextBox1.Text += text + "\r\n";

            });
            this.Invoke(invoker);
        }


        private void LoopConnect()
        {
            int attempts = 0;
            while (!_clientSocket.Connected)
            {
                try
                {
                    attempts++;
                    _clientSocket.Connect(IPAddress.Parse(textBox4.Text), 8000);

                }
                catch (SocketException)
                {
                    //Console.Clear();
                    lb_stt.Text = ("Connection attempts: " + attempts.ToString());
                }
            }
            AppendtoTextBox(reponse);
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            LoopConnect();
            // SendLoop();
            _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
            byte[] buffer = Encoding.ASCII.GetBytes("@@" + txName.Text);
            _clientSocket.Send(buffer);
        }



        private void btnSend_Click(object sender, EventArgs e)
        {
            if (_clientSocket.Connected)
            {

                byte[] buffer = Encoding.ASCII.GetBytes(txt_text.Text);
                _clientSocket.Send(buffer);
                AppendtoTextBox(txName.Text + ": " + txt_text.Text);
            }
            txt_text.Text = "";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            UserLog log = new UserLog();
            log.Show();
            this.Close();
            _clientSocket.Close();
        }
    }
}
John Denver
  • 11
  • 1
  • 7
  • 1
    Doesn't `_clientSocket.EndReceive(ar);` dispose the object? – Phiter Aug 27 '18 at 16:44
  • are you familiar with asyc process / calls also how are you even tracking the NT if you are or have created a new Thread..? are you familiar with Timers and how to start / stop the timer..check to see if the object is not null as well as if it implements IDisposable – MethodMan Aug 27 '18 at 16:45
  • 2
    Please edit your question to include a full [MCVE](https://stackoverflow.com/help/mcve). – Progman Aug 27 '18 at 16:47
  • Yes, take the time to create a minimal demo program (mcve). Close() calss Dispose() but that should not result in this exception. Odds are it's the Form that is disposed. – H H Aug 27 '18 at 16:51
  • @Phiter it dispose when it received == 0. I don't know how to use it. When I only hide the form the Socket is doubled in Server side. So I use `_clientSocket.Close();` – John Denver Aug 27 '18 at 16:57
  • @MethodMan I tried removing NT part. But when I send `-O` in server It doubles the Socket in the Checklistbox. I'm not familiar with the thread but I'm familiar with timers. When I hide and don't use the `_clientSocket.Close();` There's no popup. But I need to close it so it will not be doubled in server side. – John Denver Aug 27 '18 at 17:06
  • I'd call `_clientSocket.Close()` in the same thread (not in `NT`) and I wouldn't call `_clientSocket.BeginReceive()` after having received `"Server: -O"` (since you're about to close the socket anyway). – C.Evenhuis Aug 27 '18 at 18:02
  • @C.Evenhuis I deleted the `MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);` and there's no error message. Whats with this? – John Denver Aug 27 '18 at 18:44
  • @JohnDenver When you remove the `MessageBox` call the exception still gets caught, but you don't do anything with it, so you don't see it anymore. But the error is still there. Please edit your question to include a complete working source code which can be run by anyone, which shows the error you get (that's what it means by "complete" in https://stackoverflow.com/help/mcve). – Progman Aug 27 '18 at 19:10
  • 1
    Without your entire class we cant see whats going on, specifically the scope of `_clientSocket`. Post your 'From1' class and we could probably see whats going on. – mxmissile Aug 27 '18 at 19:37
  • @Progman Where can I put the source code? Should I edit my question? Its too long if I post it here. – John Denver Aug 27 '18 at 19:41
  • @JohnDenver You edit it into your question. You can shorten the code to remove unrelated stuff (actually you should), but it must be compilable and it must produce the error you get. Otherwise its useless when we don't see the code you have or the error you get. – Progman Aug 27 '18 at 19:46
  • @JohnDenver So you start a thread which will call `_clientSocket.Close()` to close the socket but later you will call `_clientSocket.BeginReceive()`. What do you want to do, close it or read it? It looks like you want to use `else if` statements in your `ReceiveData()` method with a final `else` statement to execute only one desired block, so you either close it OR try to read data. – Progman Aug 27 '18 at 20:07
  • @Progman I call `_clientSocket.BeginReceive()` So I can remote the client. I don't know where to put it. If I deleted it I can remote it once and the other command can't receive by the client side. Correct me if I'm wrong. – John Denver Aug 27 '18 at 20:11
  • @Progman I edited it again with 2 forms of the client side. – John Denver Aug 27 '18 at 20:12

1 Answers1

1

Like I answered in your previous question, you should spend the time to read these two pages. They will help you get your answer much faster.

There's no error in my code.

If you're getting an error message, then there's an error in your code.

every time I open and close a form

What form? There is no form in your example.

it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.

What server? What checklistbox? We don't know what you are referring to here.

Without a minimal, complete and verifiable example, we can't help you very well. That being said, it looks like you are closing your _clientSocket. Once you've closed a socket you must re-open it or create a new one before you can use it again. You cannot call BeginReceive after you've closed your socket.

I was able to reproduce your error by creating a complete, minimal and verifiable example. Here is the code:

   public partial class Form1 : Form
    {
        Socket _clientSocket;
        public Form1()
        {
            InitializeComponent();
        }

        const int buffSize = 1024;
        byte[] receivedBuf = new byte[buffSize];
        Socket listenerSock;
        Socket handlerSock;

        private void Form1_Load(object sender, EventArgs e)
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            listenerSock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listenerSock.Bind(localEndPoint);
            listenerSock.Listen(10);
            listenerSock.BeginAccept(ServerAcceptAsync, null);
            _clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _clientSocket.Connect(localEndPoint);
            _clientSocket.BeginReceive(receivedBuf, 0, buffSize, SocketFlags.None, ReceiveData, null);
        }

        private void ServerAcceptAsync(IAsyncResult ar)
        {
            handlerSock = listenerSock.EndAccept(ar);
        }

        private void ReceiveData(IAsyncResult ar)
        {
            //try
            //{
            Debug.WriteLine("received data");
                int received = _clientSocket.EndReceive(ar);
                if (received == 0)
                {
                    return;
                }
                Array.Resize(ref receivedBuf, received);
                string text = Encoding.Default.GetString(receivedBuf);
            Debug.WriteLine(text);
                if (text == "Server: -O")
                {
                    Thread NT = new Thread(() =>
                    {
                        this.BeginInvoke((Action)delegate ()
                        {
                            textBox1.Text = "Guest";
                            this.Hide();
                            _clientSocket.Close();
                            //Usertimer us = new Usertimer(textBox1.Text);
                            //us.Show();
                        });
                    });
                    NT.Start();
                }
                Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
                //AppendtoTextBox(text);
                _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var message = Encoding.UTF8.GetBytes("Server: -O");
            handlerSock.Send(message);
        }
    }

I commented the code that was not necessary to reproduce. As expected, the problem is that you call ReceiveAsync after you call _clientSock.Close(). You can't do that. If you close the socket, you should not execute anymore code. Here is an example of how to fix this:

        if (text == "Server: -O")
        {
            Thread NT = new Thread(() =>
            {
                this.BeginInvoke((Action)delegate ()
                {
                    textBox1.Text = "Guest";
                    this.Hide();
                    _clientSocket.Close();
                    //Usertimer us = new Usertimer(textBox1.Text);
                    //us.Show();
                });
            });
            NT.Start();
        }
        else
        {
            Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
            //AppendtoTextBox(text);
            _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
        }
Guillaume CR
  • 3,006
  • 1
  • 19
  • 31
  • Sorry. Form1 is the login form. When Server Sends `-O` the Client form1 will `_clientSocket.Close();` Form 2 will show and there's the popup error. Checklistbox is the one that catches all the connecting sockets and put it in the list. When I deleted the `MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);` there's no > Cannot access a disposed object. Object name: System.net.Sockets.Socket – John Denver Aug 27 '18 at 18:28
  • 2
    @JohnDenver We still need a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve). – Guillaume CR Aug 27 '18 at 18:33
  • this is my minimal, complete and verifiable example. I edited it again I hope it will be the last time. That's the shortest code that I can give, complete details that needed and the code is tested. – John Denver Aug 27 '18 at 18:42
  • @JohnDenver Answer edited, should solve your problem, but I had to do a lot of work for you. – Guillaume CR Aug 27 '18 at 20:13
  • thank you I'm tired of thinking of it. I edited my question late sorry. Having a hard time to make a complete, minimal and verifiable example. – John Denver Aug 27 '18 at 20:19
  • Thank you for you time sir but I need to take a rest, its already 4am. I hope that you're online when I woke up so I can get a knowledge from you guys. Thank you so much! God bless you! – John Denver Aug 27 '18 at 20:22
  • I'm going to understand what you've answer and I'll tell you what happens. – John Denver Aug 27 '18 at 20:24
  • Do you have a suggestion how to convert your send button into these? – John Denver Aug 28 '18 at 16:21
  • `{ for (int i = 0; i < list_Client.CheckedItems.Count; i++) { string t = list_Client.CheckedItems[i].ToString(); for (int j = 0; j < __ClientSockets.Count; j++) { if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t)) { Sendata(__ClientSockets[j]._Socket, "Server: " + Open); } } } }` – John Denver Aug 28 '18 at 16:21
  • @JohnDenver That's a new question. – Guillaume CR Aug 29 '18 at 14:11