I am testing some tcp ip based server by my test client under .net in c#.
My test client class is some trivial async socket code:
public void Connect()
{
try
{
_tcpClient.BeginConnect(IPAddress, Port, OnConnectCallBack, null);
}
catch (Exception exc)
{
Debug.Assert(false, exc.Message);
}
}
private void OnConnectCallBack(IAsyncResult ar)
{
try
{
_tcpClient.EndConnect(ar);
}
catch (Exception exc)
{
Debug.WriteLine("Connection error: " + exc.Message);
}
}
_tcpClient is a TcpClient instance.
I try to make several (100) connections to the server at a time to stress test it. If I add some 50 msec sleep between calling connect, it works like a charm. But, when I try to connect in a foreach(...) iteration without adding sleep between connections, OnConnectCallBack throws the exception: A first chance exception of type 'System.NullReferenceException' occurred in System.dll. Connection error: Object reference not set to an instance of an object. Sometimes I get target machine refuse the connection exception.
After setting a breakpoint, I noticed it comes from _tcpClient: none of its methods and property values can be seen, all of them has null reference exception value, and its Client property is null.
at TestClient.OnConnectCallBack(IAsyncResult ar) C:...\TestClient.cs(82)
at LazyAsyncResult.Complete(IntPtr userToken)
at ContextAwareResult.CompleteCallback(Object state)
at ExecutionContext.runTryCode(Object userData)
at RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at ContextAwareResult.Complete(IntPtr userToken)
at LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at LazyAsyncResult.InvokeCallback(Object result)
at QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at ThreadPoolWorkQueue.Dispatch()
at _ThreadPoolWaitCallback.PerformWaitCallback()
TcpClient
is busy in theBusyConnect()
preventing the re-entrancy? The target machine error may be a result of the server not having enough queue slots waiting in the listen(). – PekkaBeginConnect()
. Since the operation is asynchronous, it is possible that it is not safe to recall the method under all circumstances. You don't explain whether you are trying to stress test of functionally check the server. If it is the first, you could use separate instances of theTcpClient
for each connection. – Pekka