嗨,我正在寫一個簡單的服務器程序,正在偵聽連接。我的問題是,我如何測試套接字是否連接。這裏是我的代碼測試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