关闭C#套接字

时间:2015-07-03 20:21:59

标签: c# sockets

我有一个包含以下代码的按钮:

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

感谢。

1 个答案:

答案 0 :(得分:1)

你去了,虽然我应该提到你可能不想一直点击按钮,或者它会打开所有相同连接的各种套接字,或者至少抛出一个错误:

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