为什么套接字不能多次连接到同一主机?

时间:2014-07-11 13:29:38

标签: c# .net sockets

如果我们运行下面的代码,输出将是

Connecting to www.google.com
30 bytes were sent.
Connecting to www.google.com
We failed to connect!
Connecting to www.google.se
30 bytes were sent.

为什么我不能使用同一个套接字多次连接到同一主机?

(套接字似乎也有某种内存,不仅仅是它记得所有内存的最新主机......)

static void Main(string[] args)
{

    Socket client = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);
    client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
    client.SendTimeout = 500;
    Connect(client, "www.google.com");
    Connect(client, "www.google.com");
    Connect(client, "www.google.se");

    Console.ReadKey();

}

private static void Connect(Socket client, string hostName)
{
    Console.WriteLine("Connecting to " + hostName);
    IPHostEntry ipHost = Dns.GetHostEntry(hostName);
    IPAddress ipAddr = ipHost.AddressList[0];
    IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 80);

    // Connect the socket to the remote end point.
    //client.Connect(ipEndPoint);
    IAsyncResult ar = client.BeginConnect(ipEndPoint, null, null);
    ar.AsyncWaitHandle.WaitOne(5000);

    if (!client.Connected)
    {
        Console.WriteLine("We failed to connect!");
        return;
    }

    // Send some data to the remote device. 
    string data = "This is a string of data <EOF>";
    byte[] buffer = Encoding.ASCII.GetBytes(data);

    int bytesTransferred = client.Send(buffer);

    // Write to the console the number of bytes transferred.
    Console.WriteLine("{0} bytes were sent.", bytesTransferred);

    // Release the socket.
    //client.Shutdown(SocketShutdown.Both);

    client.Disconnect(true);
    if (client.Connected)
        Console.WriteLine("We failed to disconnect");
}

0 个答案:

没有答案