Search code examples
c#socketsclient

C# Socket double connect?


I was wondering, If i create a socket in C# and connect it to a server, if i create a thread in the program to try and do annother connectino with the server, will the server see 2 connections from the same place or only one?

The code would look something like this (the socket double-connecting):

IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
        Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sender.ReceiveTimeout = 5000;
        sender.Connect(remoteEP);

and then i would have below this code:

Thread thread = new Thread(new ThreadStart(doubleconnect));
            thread.Start();
public static void doubleconnect()
    {
        try
        {
            sender.Connect(remoteEP);
        }
        catch (Exception ex)
        {
        }
    }

I have this question because, on the first part of the code we connect to the server, but we dont close the connection, so by creating a thread and reconnecting i think the server will see as 2 connection from the same client.

So, would the server see this and 2 connection or just one connection?


Solution

  • Short answer: No.

    You are calling Connect twice on the same Socket. I looked in the documentation, but it says nothing about its behaviour if you do that, so I reckon two things can happen:

    1. You get an exception on the second Connect (probably a SocketException)
    2. Nothing. As the socket is already connected, it just falls through the second Connect call.

    But, why not try it out and see what happens?