2011-02-03 64 views
2

嗨,我正在寫一個簡單的服務器程序,正在偵聽連接。我的問題是,我如何測試套接字是否連接。這裏是我的代碼測試Socket是否連接在C#

using System; 
using System.Net; 
using System.Net.Sockets; 

class server 
{ 
    static int port = 0; 
    static String hostName = Dns.GetHostName(); 
    static IPAddress ipAddress; 
    static bool listening = true; 

    public static void Main(String[] args) 
    { 
     IPHostEntry ipEntry = Dns.GetHostByName(hostName); 

     //Get a list of possible ip addresses 
     IPAddress[] addr = ipEntry.AddressList; 

     //The first one in the array is the ip address of the hostname 
     ipAddress = addr[0]; 

     TcpListener server = new TcpListener(ipAddress,port); 

     Console.Write("Listening for Connections on " + hostName + "..."); 

     do 
     { 

      //start listening for connections 
      server.Start(); 



     } while (listening); 


     //Accept the connection from the client, you are now connected 
     Socket connection = server.AcceptSocket(); 

     Console.Write("You are now connected to the server"); 

     connection.Close(); 


    } 


} 
+0

你是什麼意思?你問服務器是否有任何活動連接,或者你問是否連接? – 2011-02-03 04:56:50

回答

2

我想你把豆弄糟了。在操作系統一級,有兩種截然不同的概念:一個是監聽插座 - 這就是TcpListener,和一個連接的插座 - 這就是您在成功獲得accept()後得到的結果。

現在,偵聽的TCP套接字未連接,但綁定到本地計算機上的端口(以及可能的地址)。這就是服務器等待來自客戶端的連接請求的地方。一旦這樣的請求到達,操作系統創建一個新的套接字,連接的意義在於它具有通信所需的全部四個部分 - 本地IP地址和端口以及遠程地址和端口 - 填充。

開始於一些介紹性文字,如this one。更好 - 從real one開始。

0

server.Start()應該是外循環。它只被調用一次,偵聽套接字將保持打開狀態,直到調用Stop

AcceptSocket將阻塞,直到客戶端連接。如果你想能夠接受多個套接字,那麼繼續循環它。