简体   繁体   English

关闭 C# 套接字

[英]Closing C# socket

I have a button with the following code:我有一个带有以下代码的按钮:

private void button1_Click(object sender, EventArgs e)
{
    IPHostEntry host = Dns.GetHostEntry(entered_ip);

    foreach (var address in host.AddressList)
    {
        var ipe = new IPEndPoint(address, 7779);
        var samp = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        samp.Connect(ipe);

        if (samp.Connected)
        {
            enable_anticheat();

            Process.Start("samp://" + entered_ip + ":" + entered_port);
            break;
        }
        else
        {
            continue;
        }
    }
}

I want to close the socket samp when the app closes.我想在应用程序关闭时关闭套接字samp But how can it be closed?但是怎么可能关闭呢? I understand that the socket is closed by calling samp.Close() , but if I add this in the FormClosing event for the form, I get the error element does not exist in the current context .我知道套接字是通过调用samp.Close()关闭的,但是如果我在表单的FormClosing事件中添加它,我会得到错误element does not exist in the current context

The code I am trying to use is:我尝试使用的代码是:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    samp.Close();
}

Thanks.谢谢。

There you go, although I should mention that you probably don't want to keep clicking on the button or it'll open various sockets all of the same connection or at the very least throw an error.:好了,尽管我应该提到您可能不想继续单击按钮,否则它会打开所有相同连接的各种套接字,或者至少抛出错误。:

private List<Socket> samp = new List<Socket>();

private void button1_Click(object sender, EventArgs e)
{   
        //If you don't want the error
        //if(samp.Count > 0) return;
        IPHostEntry host = null;
        Socket sock;
        host = Dns.GetHostEntry(entered_ip);

        foreach (IPAddress address in host.AddressList)
        {

            IPEndPoint ipe = new IPEndPoint(address, 7779);
            sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            sock.Connect(ipe);

            if (sock.Connected)
            {
                enable_anticheat();
                samp.Add(sock);
                Process.Start("samp://" + entered_ip + ":" + entered_port);
                break;
            } //The else continue is unnecessary. 
        }
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if(samp.Count > 0) {
      foreach(Socket s in samp) {
         s.close();             
      }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM