socket disconnecting and reconnecting (intentionally)

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
 
M

Mike Blake-Knox

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top