1

As you can see in the code below I'm calling connect with an IP and port. s.EndConnect(ar) is throwing ObjectDisposedException if the server is not running. Now if this happens I want to wait 5 seconds and retry. The problem is catching it in the ConnectCallback and calling itself doesn't work since the object IAsyncResult ar is disposed? I'm not storing the IP and port globally.

Now obviously I can store them globally and fix it that way, but I'm wondering if there's something else to fix this. Since I don't need the IP and port anywhere else storing them globally seems unnecessary.

Socket s;
public ClientSettings()
{
    s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Connect(string IP, int port)
{
    /* Simple connection method */
    try
    {
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
        s.BeginConnect(ep, new AsyncCallback(ConnectCallback), s);
    }
    catch { }
}

void ConnectCallback(IAsyncResult ar)
{
    s.EndConnect(ar);
    connected = true;
    byte[] buffer = new byte[8192];
    s.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), buffer);
}
Gerrit Iest
  • 77
  • 1
  • 10

1 Answers1

0

You're using outdated APIs. Use await with Socket and the problem goes away at much better code quality.

Or, use synchronous IO. This is appropriate if there will only be a few dozen connections at a time. This results in even easier code.

Alternatively, make IP and port instance variables. No need for globals.

usr
  • 168,620
  • 35
  • 240
  • 369
  • There might be a lot of connections, so if synchronous IO is better for that I'll try to find some more info about that. Do you maybe have a simple preview or anything on this? Also since I'm remaking it anyways now I'll work more with instance variables. – Gerrit Iest Jun 29 '15 at 22:42
  • Synchronous IO is worse with many connections because each thread consumes 1MB of stack memory. If that memory consumption is OK for then go ahead and use the more simple synchronous IO. – usr Jun 29 '15 at 22:44
  • Okay so I won't use that then. What exactly that I'm using is outdated? Got some up to date examples / documentation? – Gerrit Iest Jun 29 '15 at 22:59
  • I don't have anything handy. Search for ".net socket await". http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx looks good. You can then write code that looks like sync code but is async. – usr Jun 29 '15 at 23:01