关闭C#插座

本文关键字:插座 关闭 | 更新日期: 2023-09-27 18:01:02

我有一个按钮,代码如下:

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

我想在应用程序关闭时关闭套接字samp。但它怎么能关闭呢?我知道套接字是通过调用samp.Close()关闭的,但如果我将其添加到表单的FormClosing事件中,则会得到错误element does not exist in the current context

我尝试使用的代码是:

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

谢谢。

关闭C#插座

好了,尽管我应该提到的是,你可能不想一直点击按钮,否则它会打开同一连接的各种套接字,或者至少会抛出一个错误。:

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