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);
}
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.