You have not closed a previous connection or trying to re-connect without preparing for socket reuse.
You have to ensure that sockets are gracefully shutdown and closed. See
Graceful Shutdown, Linger Options, and Socket Closure (Windows)[
^].
Upon closing you should call the
Socket.Disconnect Method (Boolean) (System.Net.Sockets)[
^] with the
reuseSocket
parameter set. See also the example code at the above link that calls
Shutdown
first to signal the other site that the connection will be closed.
If you want to reuse a connection (using same IP and port shortly after a connection has been closed), you have to prepare the socket. Upon creation you can set the
SocketOptionName.ReuseAddress
option using the
Socket.SetSocketOption Method (SocketOptionLevel, SocketOptionName, Object) (System.Net.Sockets)[
^].
You might also set a linger time. When not doing so you have to wait until the socket is finally closed internally (usually 4 minutes). But you should not set it to very small values because that can result in losing pending data and will be a forced closing (in contrast to a graceful closing).