开发者

Test if Socket is connected in C#

Hi i am writing a simple server program that is listening for connections. My Question is, How can I test if the socket is connected or not. Here is my code

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

clas开发者_如何学Pythons 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();


    }


}


I think you got your beans messed up here. Underneath, at the OS level, there are two distinct notions: a listening socket - that's the TcpListener, and a connected socket - that's what you get after successful accept().

Now, the listening TCP socket is not connected, but bound to the port (and possibly address) on the local machine. That's where a server waits for connection requests from clients. Once such request arrives the OS creates a new socket, which is connected in a sense that it has all four parts that are required for communication - local IP address and port, and remote address and port - filled in.

Start with some introductory text, something like this one. Even better - start with a real one.


server.Start()should be outside the loop. It's only called once and the listening socket will remain open until Stop is called.

AcceptSocket will block until a client have connected. If you want to be able to accept multiple sockets, then keep looping it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜