嗨,我正在写一个简单的服务器程序,正在侦听连接。我的问题是,我如何测试套接字是否连接。这里是我的代码测试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();
}
}
你是什么意思?你问服务器是否有任何活动连接,或者你问是否连接? – 2011-02-03 04:56:50