Can TCP client reconnect to the same port in a short time in C #?

0

I have a device in which you must configure your IP and port, and also the IP and port of the PC to which you want to connect and send the data, via TCP.

The problem is that the device works as a TCP master and I must start the connection. And being the first execution of the program there is no problem, but if in less than 4 minutes (time of TIME_WAIT ) I start the program again it gives me the error:

  

Only one usage of each socket address (protocol / network address / port) is normally permitted

If I must always use the same port to send me the data, can the TCP connection of the previous execution be invalidated, or some other way to reuse the same ip-port pair in a short period of time? ?

    
asked by Ugaitz 15.07.2016 в 09:57
source

3 answers

1

You can make a TCP connection whenever you want, as many times as you want, just make sure you finish the previous connection before establishing a new one that I think is the problem for which you are having the error you mention. As a datum, it is worth mentioning the programming language in this case, since a protocol is independent of the language.

I enclose a TCP communication scheme so you can review it.

    
answered by 15.07.2016 в 15:49
0

I would like to add as information that it is very important to have an idea of what device we are talking about. In my case I had the opportunity to develop an application in .NET for a biometric fingerprint reader that worked through TCP sockets but was through an API. In this case I with a timer I consult it every X amount of seconds that I want since I do not really have to open and close the connection to consult.

The latter can also be useful, change the way you work so that the program does not close and open but keep and consult or write.

Just a humble opinion.

Greetings.

    
answered by 15.07.2016 в 16:57
0

You can start the following connections using other ports, avoiding the failure.

The connections use ports by protocols, so the applications / performances keep an order not to interfere with each other, this is the same reason why you can not have two connections with the same - network protocol, address and port -.

TCP connections use acknowledgment for data packets, so by forcing the process to close, the transfer may be incomplete. To close the process properly, it should be controlled that the data transfers have been completed, that no transfer processes remain in progress, closing the connection in an orderly manner. Or force the closure knowing that transfers can be truncated, aware of what it entails, if what we want at that moment is precisely to abort the session (by port and directions).

To close a connection in C # with TcpClient, it would be like this:

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

...
...
   networkStream.Close();
   tcpClient.Close();
...
    
answered by 15.07.2016 в 15:49