Reputation: 776
Well, I wonder if some one can help with a problem that I encounter....
I want to close a socket and then rerun from the same port. This is what i am doing...
opening:
UdpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
UdpServerIpEndPoint = new IPEndPoint(IPAddress.Any, 9050);
UdpEndPoint = (EndPoint)UdpServerIpEndPoint;
UdpServer.Bind(UdpServerIpEndPoint);
closeing:
UdpServer.Shutdown(SocketShutdown.Both);
UdpServer.Disconnect(true);
UdpServer.Close();
After I close it. and the I try to reconnect it with the same code as above, I get error:
Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted
I checked for exception during closing, but I didnt get any, i guessed they were closed properly, so actually, what is causing this problem? Please help!
Upvotes: 11
Views: 15122
Reputation: 2404
For reference, in case anyone else stumbles onto this question but looking for the UdpClient implementation.
int port = 1234;
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
var endPoint = new IPEndPoint(IPAddress.Any, port);
socket.Bind(endPoint);
var updClient = new UdpClient();
updClient.Client = socket;
updClient.Connect(_ipAddress, port);
Upvotes: 0
Reputation: 776
I got answer.... I need to use this after decleration of socket...
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);
Upvotes: 17
Reputation: 4768
You could look at this 2 ways.
Don't actually Receive whilst your are in your stopped state, just in your BeginReceive, just drop/ignore the data
If you really need to recreate the socket, then don't perform the disconnect on your Server because you haven't actually got a connection. Your disconnect is throwing
System.Net.Sockets.SocketException (0x80004005): A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
Upvotes: 0