2015-07-03 73 views
-1

我用下面的代码按钮:闭幕C#插座

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

感谢。

+0

你的变量套接字应该作为你的类的成员在函数之外声明。 – MiltoxBeyond

+0

我知道,但如何?请帮助:( – Dewagg

回答

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

哇,太谢谢你了,但这里的一些错误:(http://prntscr.com/7ohijz – Dewagg

+0

Woops刚在Java编程中,它应该是'的foreach(在SAMP插座S){' – MiltoxBeyond

+0

没错,谢谢你,所以muuuuch! – Dewagg