socket disconnecting and reconnecting (intentionally)

  • Thread starter Thread starter Joshua Moore
  • Start date Start date
J

Joshua Moore

Here's the C# code:

----

socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

socket.Blocking = true;

EndPoint sender = new IPEndPoint(IPAddress.Any, 2222);

socket.Bind(sender);

----

I need to stop reading in packets and stop the packets from being read into the queue, but then be able to reconnect the socket.

Currently, I use:

----

public void UnBind()

socket - null;

public void ReBind()

socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

socket.Blocking = true;

EndPoint sender = new IPEndPoint(IPAddress.Any, 2068);

socket.Bind(sender);

-----

When I call "ReBind", it gives the error "Only one usage of each socket address(protocol/network address/port) is normally permitted".

Any help would be greatly appreciated.

Joshua Moore
 
I need to stop reading in packets and stop the packets from being
read into the queue, but then be able to reconnect the socket.

When I call "ReBind", it gives the error "Only one usage of each
socket address(protocol/network address/port) is normally
permitted".


When you close a bound socket you cannot immediately reopen it as the
TCP stack can't tell whether a packet it receives belongs to the closed
connection or the one that's being opened. Use
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress, 1) before you bind to the socket.

This behavior occurs even if a different program tries to do the bind
so it's a good practice to always use ReuseAddress before binding.

Mike Blake-Knox
 
Back
Top