[英]Closing C# socket
我有一个带有以下代码的按钮:
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();
}
谢谢。
好了,尽管我应该提到您可能不想继续单击按钮,否则它会打开所有相同连接的各种套接字,或者至少抛出错误。:
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.