Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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("
Server: " + 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("
" + __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("
Server: " + 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("
Server: " + 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;
                 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...