I have two servers and a client. One server is on the same computer where the client is. I need to disconnect from the local server and connect to the remote one.
AutoResetEvent disconnectDone = new AutoResetEvent(false);
IPEndPoint localEndPoint = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], PORT);
Socket socket;
// somewhere I initialize the socket and connect to the local end point
public void someButton_Click(object sender, EventArgs e)
{
string IP = someTextBox.Text;
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
socket.BeginDisconnect(true, DisconnectCallback, socket);
disconnectDone.WaitOne();
}
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), PORT);
socket.BeginConnect(remoteEndPoint, ConnectCallback, socket);
}
private void DisconnectCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndDisconnect(AR);
disconnectDone.Set();
}
It freezes at the line with the WaitOne method because DisconnectCallback doesn't answer. If in the BeginDisconnect method I change true to false then it "works". But further BeginConnect gives me an exception that the socket is still connected.
I really do not understand how all these disconnect things work. Or maybe I'm wrong with those thread methods (WaitOne and Set). Please help!