2012-11-03 58 views
3

編譯時出現此錯誤。這是什麼意思,我該如何解決它?'System.Net.Sockets.Socket.Dispose(布爾)'由於其保護級別而無法訪問

「System.Net.Sockets.Socket.Dispose(布爾)」不可訪問由於其保護級別

這裏是我的兩個文件;

Listener.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
namespace Multi_con_Server 
{ 
class Listener 
{ 
    Socket s; 

    public bool Listening 
    { 
     get; 
     private set; 
    } 
    public int Port 
    { 
     get; 
     private set; 
    } 

    public Listener(int port) 
    { 
     Port = port; 
     s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
    } 
    public void Start() 
    { 
     if (Listening) 
      return; 
     s.Bind(new IPEndPoint(0, Port)); 
     s.Listen(0); 

     s.BeginAccept(callback, null); 
     Listening = true; 
    } 
    public void Stop() 
    { 
     if (!Listening) 
      return; 

     s.Close(); 
     s.Dispose(); 
     s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
    } 

    void callback(IAsyncResult ar) 
    { 
     try 
     { 
      Socket s = this.s.EndAccept(ar); 

      if (SocketAccepted != null) 
      { 
       SocketAccepted(s); 
      } 

      this.s.BeginAccept(callback, null); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 

    } 
    public delegate void SocketAccecptedHandler(Socket e); 
    public event SocketAccecptedHandler SocketAccepted; 

} 
} 

的Program.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
namespace Multi_Con_C 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,  
    ProtocolType.Tcp); 
     s.Connect("127.0.0.1", 8); 
     s.Close(); 
     s.Dispose(); 
    } 
} 
} 

回答

4

MSDNSocket.Close()自動 「釋放所有相關的資源。」您可以安全地從您的代碼中刪除所有發生的Socket.Dispose()

+0

謝謝。那工作。 :D – Herzatyl

+0

沒問題! :) –

相關問題