1

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!

J. Doe
  • 229
  • 3
  • 15
  • Lots of problems here. **1)** what's the point of using `BeginDisconnect()` if all you're going to do is wait for it? Just call `Disconnect()`. **2)** since you want to reuse the socket, the network stack _might_ be assuming you're going to handle the graceful closure correctly, by reading from the socket until you reach end-of-stream (receive byte count of 0). How long have you waited to see if the disconnect completes? it may be you're just waiting on a wait state on the socket, due to the improper closure. **3)** it's not clear why you're using disconnect anyway. – Peter Duniho Dec 31 '17 at 06:30
  • IMHO, you should change the code so that it properly closes the socket by reading from it until you get a 0 return value on the byte count, and so that you just create a new socket instead of trying to reuse the old one (this idea of socket reuse is really only valuable for very high-throughput server implementations). Since you didn't post a [mcve] that reproduces your problem, it's not practical to try to actually post an answer. – Peter Duniho Dec 31 '17 at 06:30
  • Thank you for your answer. I found the solution. And now I understand that my code was insufficient. The problem was on server, where it accepted received packets. It just threw an exception when I got 0 bytes. – J. Doe Dec 31 '17 at 07:03
  • @PeterDuniho -1) that is the official guidance from microsoft sample code https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.begindisconnect?redirectedfrom=MSDN&view=netframework-4.7.2#System_Net_Sockets_Socket_BeginDisconnect_System_Boolean_System_AsyncCallback_System_Object_ – Karan Harsh Wardhan Apr 10 '19 at 06:33
  • @kkarakk: you should not take Microsoft example code as _"official guidance"_. It is not. It's there to demonstrate particular techniques, and _often_ has contrived architecture that exists solely for the purpose of demonstration. And the networking API documentation includes some of the most misleading of this type of example. – Peter Duniho Apr 10 '19 at 14:19
  • @PeterDuniho please recommend a good source then coz i've been using the example code in production – Karan Harsh Wardhan Apr 11 '19 at 06:40
  • 1
    @kkarakk: I'm not sure there are any truly great resources. That said, socket programmers should start here: https://tangentsoft.net/wskfaq/. I myself have posted several examples of socket code on SO; for example, https://stackoverflow.com/a/43431682 and https://stackoverflow.com/a/26917806. Not sure if either specifically address the async disconnect aspect though. I didn't do a thorough search; you can see if any of my other posts have something of use. ... – Peter Duniho Apr 11 '19 at 07:58
  • 1
    @kkarakk: … I also long ago wrote a few blog articles on the topic, when I foolishly thought I had time to write a blog: https://blogs.msmvps.com/duniho/2008/08/19/basic-network-programming-in-net/ – Peter Duniho Apr 11 '19 at 07:58

0 Answers0