2016-09-19 71 views
1

我在互聯網上發現了這段代碼: 它並沒有打開監聽端口11000的服務器,正如我所希望的。 問題是什麼?我通常編碼德爾福,所以我有點迷路。 我在Delphi中做了一個相應的客戶端,它的工作原理。C#中的Tcp Socket服務器#

我使用的C#2015

public static void StartListening() 
    { 
     // Data buffer for incoming data. 
     byte[] bytes = new Byte[1024]; 

     // Establish the local endpoint for the socket. 
     // Dns.GetHostName returns the name of the 
     // host running the application. 
     IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
     IPAddress ipAddress = ipHostInfo.AddressList[0]; 
     IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 

     // Create a TCP/IP socket. 
     Socket listener = new Socket(AddressFamily.InterNetwork, 
      SocketType.Stream, ProtocolType.Tcp); 

     // Bind the socket to the local endpoint and 
     // listen for incoming connections. 
     try 
     { 
      listener.Bind(localEndPoint); 
      listener.Listen(10); 

      // Start listening for connections. 
      while (true) 
      { 
       //Console.WriteLine("Waiting for a connection..."); 
       // Program is suspended while waiting for an incoming connection. 
       Socket handler = listener.Accept(); 
       data = null; 

       // An incoming connection needs to be processed. 
       while (true) 
       { 
        bytes = new byte[1024]; 
        int bytesRec = handler.Receive(bytes); 
        data += Encoding.ASCII.GetString(bytes, 0, bytesRec); 
        if (data.IndexOf("#") > -1) 
        { 
         break; 
        } 
       } 

       // Show the data on the console. 
       //Console.WriteLine("Text received : {0}", data); 

       // Echo the data back to the client. 
       byte[] msg = Encoding.ASCII.GetBytes(data); 

       handler.Send(msg); 
       handler.Shutdown(SocketShutdown.Both); 
       handler.Close(); 
      } 

     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 

     //Console.WriteLine("\nPress ENTER to continue..."); 
     //Console.Read(); 

    } 
+0

「bind」有什麼例外? – Prabhu

+0

嗨,我有一個客戶端和服務器的例子https://github.com/vtortola/AynchronousTCPListener – vtortola

+0

非常感謝。綁定沒有例外。 –

回答

3

的問題可能會在這裏演示版本:什麼的ipHostInfo.AddressList[0]的IP地址?這可能是環回。除非需要,否則我絕不會將服務器端點限制爲IP地址,但我會在配置文件中指定它。

IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 11000); 
+1

這就是問題所在,非常感謝。 –

0

感謝您的反饋。我發現索姆其他,舊代碼:

TcpListener serverSocket = new TcpListener(11000); 

這樣做的工作。我知道這是貶值,但實際上它起作用。

+1

如果你看看[代碼](http://referencesource.microsoft.com/#System/net/System/Net/Sockets/TCPListener.cs,b4b3fb30f684759a),你會發現它和@完全一樣Jeroen在他的回答中提到。所以你應該至少上傳他的答案和/或接受它。 – Oliver

+0

好的,很難找到按鈕... –