2015-07-03 79 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