无法访问已处置的对象C#

时间:2018-08-27 16:41:53

标签: c#

我很难受。我是新来的。有人可以帮我弄这个吗。每次我致电_clientSocket.Close();时,都会收到一条错误消息。

  

无法访问已处置的对象。对象名称:   System.net.Sockets.Socket

我的代码没有错误。它可以顺利运行,但是每次我打开和关闭表单时都会出现。我想摆脱它。该程序可以运行,但是很烦人。因为当我尝试打开客户端时,它将弹出。并且,当客户端的时间结束时,该表单将关闭,并且登录名会弹出

  

无法访问已处置的对象。对象名称:   System.net.Sockets.Socket

我使用_clientSocket.Close()是因为如果我不关闭套接字,它将在服务器端加倍。我将其关闭,因此它不会是服务器复选框中的双重IP。

我正在为我的项目做这件事,我只是在学习自己,所以我真的听不懂一些评论,但我正在努力学习,谢谢!!

您的建议将不胜感激。如果我错了请纠正我,谢谢!

当服务器发送-O并将_clientSocket.Close();并打开Form2时,此代码是Loginform。如果Form2一直使用,它将返回Loginform和form2 _clientSocket.Close();,我之所以叫_clientSocket.Close();,是因为如果我不关闭套接字,捕获所有已连接套接字的服务器清单框将加倍。 >

已编辑

服务器

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


        }
    }

客户

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

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

1 个答案:

答案 0 :(得分:1)

就像我在your previous question中回答的那样,您应该花时间阅读these two页。他们将帮助您更快地获得答案。

  

我的代码没有错误。

如果收到错误消息,则说明您的代码中有错误。

  

每次我打开和关闭表单

什么形式?您的示例中没有表格。

  

它将在服务器端加倍。我将其关闭,因此在服务器的复选框中不会是双IP。

什么服务器?什么复选框?我们不知道您在这里指的是什么。

没有一个简短,完整和可验证的示例,我们不能很好地帮助您。话虽如此,看来您正在关闭_clientSocket。关闭插座后,必须重新打开它或创建一个新插座,然后才能再次使用它。关闭套接字后,您将无法调用BeginReceive。

我能够通过创建一个完整,最少和可验证的示例来重现您的错误。这是代码:

render(){
    <FlatList 
        renderItem={(props) => {
            return(
               <this.props.customCell extraData={this.suggestData}/>
            )
        }}
     />
}

我评论了不需要复制的代码。不出所料,问题在于您调用_clientSock.Close()之后调用了ReceiveAsync 。你不能那样做。如果关闭套接字,则不应再执行代码。这是解决此问题的示例:

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