2011-02-03 60 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将阻塞,直到客户端连接。如果你想能够接受多个套接字,那么继续循环它。