2011-02-17 72 views
1

我已經做了一個TCP服務器,我一直在本地測試,它的工作很好,現在我打開了防火牆上的端口,但我仍然無法看到外部的端口。我認爲這取決於我的套接字的配置,我該如何解決這個問題?c#.net打開一個外部tcp端口

 System.Net.IPHostEntry localhost = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); 

     #region Bind Socket & Listen for connections, accepting Asynchronously 

     System.Net.IPEndPoint serverEndPoint; 

     try 
     { 
      serverEndPoint = new System.Net.IPEndPoint(localhost.AddressList[0], _port); 
     } 
     catch (System.ArgumentOutOfRangeException e) 
     { 
      throw new ArgumentOutOfRangeException("Port number entered would seem to be invalid, should be between 1024 and 65000", e); 
     } 

     try 
     { 
      //_serverSocket = new System.Net.Sockets.Socket(serverEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
      //_serverSocket = new System.Net.Sockets.Socket(serverEndPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
      //_serverSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
      _serverSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     } 
     catch (System.Net.Sockets.SocketException e) 
     { 
      throw new ApplicationException("Could not create socket, check to make sure not duplicating port", e); 
     } 

     try 
     { 
      _serverSocket.Bind(new IPEndPoint(IPAddress.Any/*.Parse("127.0.0.1")*/, _port));//serverEndPoint); 
      //_serverSocket.Bind(new System.Net.IPEndPoint(System.Net.Dns.GetHostEntry("localhost").AddressList[0],12345)); 
      _serverSocket.Listen(_backlog); 
     } 
     catch (Exception e) 
     { 
      throw new ApplicationException("Error occured while binding socket, check inner exception", e); 
     } 

     try 
     { 
      //warning, only call this once, this is a bug in .net 2.0 that breaks if 
      // you're running multiple asynch accepts, this bug may be fixed, but 
      // it was a major pain in the ass previously, so make sure there is only one 
      //BeginAccept running 
      _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), _serverSocket); 
     } 
     catch (Exception e) 
     { 
      throw new ApplicationException("Error occured starting listeners, check inner exception", e); 
     } 

     #endregion 
+1

類型netstat -a檢驗服務器是否UP與IP /端口是聽我沒有配置端口轉發。 – 2011-02-17 15:58:09

+0

感謝netstat提示! – Chris 2011-02-17 16:06:04

回答

0

插座配置是正確的 - 使用正確的IP子網