简体   繁体   English

C#套接字双重连接?

[英]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? 我想知道,如果我在C#中创建一个套接字并将其连接到服务器,如果我在程序中创建了一个线程来尝试与服务器进行另一个connectino,则服务器会从同一位置看到2个连接还是只有一个?

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. 我有这个问题,因为在代码的第一部分中,我们连接到服务器,但是我们没有关闭连接,因此通过创建线程并重新连接,我认为服务器会将同一客户端视为2连接。

So, would the server see this and 2 connection or just one connection? 那么,服务器会看到这两个连接还是一个连接?

Short answer: No. 简短答案:不可以。

You are calling Connect twice on the same Socket . 您在同一Socket上两次调用Connect 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 ) 您在第二个Connect上遇到异常(可能是SocketException
  2. Nothing. 没有。 As the socket is already connected, it just falls through the second Connect call. 由于套接字已连接,因此只能通过第二个Connect调用。

But, why not try it out and see what happens? 但是,为什么不尝试一下,看看会发生什么呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM