测试Socket是否在C#中连接

时间:2011-02-03 04:16:52

标签: c# sockets networking

您好我正在编写一个正在侦听连接的简单服务器程序。我的问题是,如何测试套接字是否已连接。这是我的代码

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();


    }


}

2 个答案:

答案 0 :(得分:2)

我觉得你的豆子搞砸了。在下面,在操作系统级别,有两个不同的概念:监听套接字 - 即TcpListener连接套接字 - 这就是你成功后获得的accept()

现在,侦听TCP套接字未连接,但绑定到本地计算机上的端口(可能还有地址)。这就是服务器等待来自客户端的连接请求的地方。一旦这样的请求到达,操作系统就会创建一个新的套接字,它连接的意思是它具有通信所需的全部四个部分 - 本地IP地址和端口,以及填写的远程地址和端口。

从一些介绍性文字开始,例如this one。更好 - 从real one开始。

答案 1 :(得分:0)

server.Start()应该在循环之外。它只被调用一次,监听套接字将一直打开,直到调用Stop

AcceptSocket将阻止,直到客户端已连接。如果你想能够接受多个套接字,那么继续循环它。

相关问题