I need a method that attempts to connect to the server until it successfully connects. I've done so successfully with Socket.Connect but I can't get it to work with Socket.BeginConnect.
This is the method:
public void Start()
{
while (clientSocket == null || !clientSocket.Connected)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.BeginConnect(serverEndPoint, new AsyncCallback(ConnectCallback), null);
}
catch (SocketException)
{
clientSocket.Close();
Start();
}
catch (Exception) { throw; }
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
clientSocket.EndConnect(ar);
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception) { throw; }
}
But I get this error (multiple times):
System.ArgumentException: The IAsyncResult object was not returned
from the corresponding asynchronous method on this class. Parameter
name: asyncResult at
System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at
SocketLibrary.Client.TCPClient.ConnectCallback(IAsyncResult ar) at
System.Net.LazyAsyncResult.Complete(IntPtr userToken) at
System.Net.ContextAwareResult.CompleteCallback(Object state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Net.ContextAwareResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at System.Net.Sockets.Socket.ConnectCallback() at
System.Net.Sockets.Socket.RegisteredWaitCallback(Object state, Boolean
timedOut) at
System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Object
state, Boolean timedOut)
I tried catching the ArgumentException but then I got this error (multiple times again)
Unhandled Exception: System.NullReferenceException: Object reference
not set to an instance of an object. at
SocketLibrary.Client.TCPClient.ConnectCallback(IAsyncResult ar) at
System.Net.LazyAsyncResult.Complete(IntPtr userToken) at
System.Net.ContextAwareResult.CompleteCallback(Object state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Net.ContextAwareResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at System.Net.Sockets.Socket.ConnectCallback() at
System.Net.Sockets.Socket.RegisteredWaitCallback(Object state, Boolean
timedOut) at
System.Threading._ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Object
state, Boolean timedOut)
I'm fairly new to working with sockets (and I've only been programming for a couple of months) so I'm sure I'm going about this entirely wrong so I'd appreciate any help/suggestions.
Since you haven't posted complete code, I am assuming you are trying to use global client object. In the ConnectCallback, you need to first retrieve and typecast the client object into a Socket. So in your case, it would be:
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
client = (Socket) ar.AsyncState;
//In case, you are using local client object
//Socket client = (Socket) ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
The above code is taken from this MSDN example, have a look at it. If you fix, the first step in your approach, it should work.
Related
We have a WPF client that connects with SignalR to one of our servers. When closing the WPF client we also close the SignalR HubConnection:
public HubConnection Connection => _connection ??= GetConnection();
private HubConnection GetConnection()
{
var host = ConfigurationManager.AppSettings["SignalRHost"];
var connection = new HubConnectionBuilder()
.WithUrl(host)
.Build();
connection.Closed += ConnectionOnClosed;
return connection;
}
private async Task ConnectionOnClosed(Exception exception)
{
// The connection is disconnected
if (_disconnecting)
{
// The disconnect was requested by the client
Connection.Closed -= ConnectionOnClosed;
Logger.Information("The connection to SignalR hub was closed.");
}
else
{
await StartAsync();
}
}
public async Task Disconnect()
{
if (_disconnecting) return;
try
{
_disconnecting = true;
await _connection.StopAsync();
}
catch (Exception e)
{
Logger.Error(e, "Error in closing connection");
}
finally
{
await _connection.DisposeAsync();
_connection = null;
}
}
Calling CloseAsync results in two ObjectDisposedExceptions. I only have a partial stacktrace (that seems to be another problem in my VS):
System.dll!System.Net.Sockets.NetworkStream.InternalSocket.get() Line 136
System.dll!System.Net.PooledStream.CancelPendingIoAndCloseIfSafe(bool closeWithTimeout, int timeout) Line 596
System.dll!System.Net.PooledStream.Close(int timeout) Line 682
System.dll!System.Net.Connection.AbortOrDisassociate(System.Net.HttpWebRequest request, System.Net.WebException webException) Line 2859
System.dll!System.Net.HttpWebRequest.Abort(System.Exception exception, int abortState) Line 3173
System.dll!System.Net.HttpWebRequest.Abort() Line 3133
System.dll!System.Net.WebSockets.ClientWebSocket.AbortRequest(object obj) Line 366
mscorlib.dll!System.Threading.CancellationCallbackInfo.ExecutionContextCallback(object obj) Line 1031
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Line 980
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Line 928
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Line 917
mscorlib.dll!System.Threading.CancellationCallbackInfo.ExecuteCallback() Line 1021
mscorlib.dll!System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(System.Threading.CancellationCallbackCoreWorkArguments args) Line 863
mscorlib.dll!System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(bool throwOnFirstException) Line 808
mscorlib.dll!System.Threading.CancellationTokenSource.NotifyCancellation(bool throwOnFirstException) Line 743
System.dll!System.Net.WebSockets.ClientWebSocket.Dispose() Line 377
System.dll!System.Net.WebSockets.ClientWebSocket.Abort() Line 360
Microsoft.AspNetCore.Http.Connections.Client.dll!Microsoft.AspNetCore.Http.Connections.Client.Internal.WebSocketsTransport.ProcessSocketAsync(System.Net.WebSockets.WebSocket socket) Line 220
And the next:
> System.dll!System.Net.Sockets.NetworkStream.InternalSocket.get() Line 136 C#
System.dll!System.Net.PooledStream.CancelPendingIoAndCloseIfSafe(bool closeWithTimeout, int timeout) Line 596 C#
System.dll!System.Net.PooledStream.Close(int timeout) Line 682 C#
System.dll!System.Net.Connection.AbortSocket(bool isAbortState) Line 2901 C#
System.dll!System.Net.ConnectStream.CloseInternal(bool internalCall, bool aborting) Line 2707 C#
System.dll!System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(System.Net.CloseExState closeState) Line 2426 C#
System.dll!System.Net.HttpWebResponse.Abort() Line 479 C#
System.dll!System.Net.HttpWebRequest.SetResponse(System.Exception E) Line 3968 C#
System.dll!System.Net.HttpWebRequest.SetAndOrProcessResponse(object responseOrException) Line 3661 C#
System.dll!System.Net.ConnectionReturnResult.SetResponses(System.Net.ConnectionReturnResult returnResult) Line 205 C#
System.dll!System.Net.Connection.AbortOrDisassociate(System.Net.HttpWebRequest request, System.Net.WebException webException) Line 2873 C#
System.dll!System.Net.HttpWebRequest.Abort(System.Exception exception, int abortState) Line 3173 C#
System.dll!System.Net.HttpWebRequest.Abort() Line 3133 C#
System.Net.Http.dll!System.Net.Http.HttpClientHandler.OnCancel(object state) Line 1210 C#
mscorlib.dll!System.Threading.CancellationCallbackInfo.ExecutionContextCallback(object obj) Line 1031 C#
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Line 980 C#
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Line 928 C#
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Line 917 C#
mscorlib.dll!System.Threading.CancellationCallbackInfo.ExecuteCallback() Line 1021 C#
mscorlib.dll!System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(System.Threading.CancellationCallbackCoreWorkArguments args) Line 863 C#
mscorlib.dll!System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(bool throwOnFirstException) Line 808 C#
mscorlib.dll!System.Threading.CancellationTokenSource.NotifyCancellation(bool throwOnFirstException) Line 743 C#
mscorlib.dll!System.Threading.CancellationTokenSource.LinkedTokenCancelDelegate(object source) Line 91 C#
mscorlib.dll!System.Threading.CancellationCallbackInfo.ExecutionContextCallback(object obj) Line 1031 C#
mscorlib.dll!System.Threading.CancellationCallbackInfo.ExecuteCallback() Line 1021 C#
mscorlib.dll!System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(System.Threading.CancellationCallbackCoreWorkArguments args) Line 863 C#
mscorlib.dll!System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(bool throwOnFirstException) Line 808 C#
mscorlib.dll!System.Threading.CancellationTokenSource.NotifyCancellation(bool throwOnFirstException) Line 743 C#
mscorlib.dll!System.Threading.CancellationTokenSource.TimerCallbackLogic(object obj) Line 534 C#
mscorlib.dll!System.Threading.TimerQueueTimer.CallCallbackInContext(object state) Line 730 C#
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Line 980 C#
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Line 928 C#
mscorlib.dll!System.Threading.TimerQueueTimer.CallCallback() Line 713 C#
mscorlib.dll!System.Threading.TimerQueueTimer.Fire() Line 670 C#
mscorlib.dll!System.Threading.TimerQueue.FireQueuedTimerCompletion(object state) Line 444 C#
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() Line 1252 C#
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Line 820 C#
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Line 1161 C#
The server is running in Visual Studio at http://localhost:5008/tubahub. When running the server in IIS on the same machine we also get a SocketException when calling StopAsync due to a timeout. Perhaps that is related.
My Server (System.Net) is working on my local mashine (win10), but not on the ubuntu server, i get this error:
Unhandled exception. System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'size')
at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
at Server.Client.Start() in C:\Users\xxxx\source\repos\Server\Server\Client.cs:line 28
at Server.ClientManager.CreateNewConnection(TcpClient tempClient) in C:\Users\xxxx\source\repos\Server\Server\ClientManager.cs:line 19
at Server.Server.OnClientConnect(IAsyncResult result) in C:\Users\xxxx\source\repos\Server\Server\Server.cs:line 61
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.ContextAwareResult.CompleteCallback()
at System.Net.ContextAwareResult.<>c.<Complete>b__15_0(Object s)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionCallback(Int32 numBytes, SocketError errorCode)
at System.Net.Sockets.AcceptOverlappedAsyncResult.CompletionCallback(IntPtr acceptedFileDescriptor, Byte[] socketAddress, Int32 socketAddressLen, SocketError errorCode)
at System.Net.Sockets.SocketAsyncContext.AcceptOperation.InvokeCallback(Boolean allowPooling)
at System.Net.Sockets.SocketAsyncContext.OperationQueue`1.ProcessAsyncOperation(TOperation op)
at System.Net.Sockets.SocketAsyncContext.ReadOperation.System.Threading.IThreadPoolWorkItem.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Aborted (core dumped)
this is the code thats causing the error (its working on my local):
socket.SendBufferSize = 4096;
socket.ReceiveBufferSize = 4096;
stream = socket.GetStream();
recBuffer = new byte[4096];
stream.BeginRead(recBuffer, 0, socket.ReceiveBufferSize, OnReceiveData, null);
Console.WriteLine($"Connection from {socket.Client.RemoteEndPoint.ToString()}");
when i listen with netcat to the port im using (55555) and connect in the game, the connection works, so i think the port/firewall is fine.
i tried exporting it as a linux build, and as a windows build, which i executed via wine, both didn't work.
this is how i published it:
publish
I have a WCF service(selfhosted) and client, the client uses client certificate and the service uses a service certificate over HTTPS. This works fine on computer but the other throws this :
System.ServiceModel.Security.MessageSecurityException: The HTTP request was forbidden with client authentication scheme 'Anonymous'. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
--- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.<>c__DisplayClass7_0`1.<CreateGenericTask>b__0(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Myapp.Client.Main.ServiceManagement.ServiceAgents.General.<GetUserConfigurations>d__5.MoveNext() in C:\Project\Myapp\Produkter\MyappUtveckling\Solution\Myapp.Client.Main\Classes\Service Management\Service Agents\General.cs:line 172
In the WCF log I can see this :
Configuration evaluation context not found.
http://msdn.microsoft.com/sv-SE/library/System.ServiceModel.Channels.HttpChannelUnexpectedResponse.aspx
Received bad HTTP response
Myapp.vshost.exe
System.ServiceModel.Security.MessageSecurityException,
System.ServiceModel, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089 The HTTP
request was forbidden with client authentication scheme
'Anonymous'. at
System.ServiceModel.Channels.HttpChannelUtilities.TraceResponseException(Exception
exception) at
System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest
request, HttpWebResponse response, WebException responseException,
HttpChannelFactory1 factory) at
System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest
request, HttpWebResponse response, HttpChannelFactory1 factory,
WebException responseException, ChannelBinding channelBinding) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.ProcessResponse(HttpWebResponse
response, WebException responseException) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult
result) at
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult
result) at System.Net.LazyAsyncResult.Complete(IntPtr userToken) at
System.Net.ContextAwareResult.CompleteCallback(Object state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Net.ContextAwareResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at System.Net.HttpWebRequest.ProcessResponse() at
System.Net.HttpWebRequest.SetResponse(CoreResponseData
coreResponseData) at
System.Net.HttpWebRequest.SetAndOrProcessResponse(Object
responseOrException) at
System.Net.ConnectionReturnResult.SetResponses(ConnectionReturnResult
returnResult) at System.Net.Connection.ReadComplete(Int32 bytesRead,
WebExceptionStatus errorStatus) at
System.Net.Connection.ReadCallback(IAsyncResult asyncResult) at
System.Net.Connection.ReadCallbackWrapper(IAsyncResult asyncResult) at
System.Net.LazyAsyncResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at
System.Net.Security._SslStream.ProcessFrameBody(Int32 readBytes,
Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest
asyncRequest) at
System.Net.Security._SslStream.ReadFrameCallback(AsyncProtocolRequest
asyncRequest) at System.Net.AsyncProtocolRequest.CompleteRequest(Int32
result) at
System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
at System.Net.FixedSizeReader.ReadCallback(IAsyncResult
transportResult) at System.Net.LazyAsyncResult.Complete(IntPtr
userToken) at System.Net.ContextAwareResult.CompleteCallback(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Net.ContextAwareResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at
System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace>
<ExceptionString>System.ServiceModel.Security.MessageSecurityException:
The HTTP request was forbidden with client authentication scheme
'Anonymous'. ---> System.Net.WebException: The remote server
returned an error: (403) Forbidden. at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result) --- End of inner exception stack trace
--- System.Net.WebException, System, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089
The remote server returned an error: (403)
Forbidden. at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result) </StackTrace> <ExceptionString>System.Net.WebException: The
remote server returned an error: (403) Forbidden. at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result)
http://msdn.microsoft.com/sv-SE/library/System.ServiceModel.Diagnostics.ThrowingException.aspx
Throwing an exception.
Myapp.vshost.exe
System.ServiceModel.Security.MessageSecurityException,
System.ServiceModel, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089 The HTTP
request was forbidden with client authentication scheme
'Anonymous'. at
System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest
request, HttpWebResponse response, WebException responseException,
HttpChannelFactory1 factory) at
System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest
request, HttpWebResponse response, HttpChannelFactory1 factory,
WebException responseException, ChannelBinding channelBinding) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.ProcessResponse(HttpWebResponse
response, WebException responseException) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult
result) at
System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult
result) at System.Net.LazyAsyncResult.Complete(IntPtr userToken) at
System.Net.ContextAwareResult.CompleteCallback(Object state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Net.ContextAwareResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at System.Net.HttpWebRequest.ProcessResponse() at
System.Net.HttpWebRequest.SetResponse(CoreResponseData
coreResponseData) at
System.Net.HttpWebRequest.SetAndOrProcessResponse(Object
responseOrException) at
System.Net.ConnectionReturnResult.SetResponses(ConnectionReturnResult
returnResult) at System.Net.Connection.ReadComplete(Int32 bytesRead,
WebExceptionStatus errorStatus) at
System.Net.Connection.ReadCallback(IAsyncResult asyncResult) at
System.Net.Connection.ReadCallbackWrapper(IAsyncResult asyncResult) at
System.Net.LazyAsyncResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at
System.Net.Security._SslStream.ProcessFrameBody(Int32 readBytes,
Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest
asyncRequest) at
System.Net.Security._SslStream.ReadFrameCallback(AsyncProtocolRequest
asyncRequest) at System.Net.AsyncProtocolRequest.CompleteRequest(Int32
result) at
System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
at System.Net.FixedSizeReader.ReadCallback(IAsyncResult
transportResult) at System.Net.LazyAsyncResult.Complete(IntPtr
userToken) at System.Net.ContextAwareResult.CompleteCallback(Object
state) at
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Net.ContextAwareResult.Complete(IntPtr userToken) at
System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result,
IntPtr userToken) at
System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) </StackTrace>
<ExceptionString>System.ServiceModel.Security.MessageSecurityException:
The HTTP request was forbidden with client authentication scheme
'Anonymous'. ---> System.Net.WebException: The remote server
returned an error: (403) Forbidden. at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result) --- End of inner exception stack trace
--- System.Net.WebException, System, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089
The remote server returned an error: (403)
Forbidden. at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result) </StackTrace> <ExceptionString>System.Net.WebException: The
remote server returned an error: (403) Forbidden. at
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at
System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult
result)
My first thougt was certificates but both computers matches.
Im creating the channel on the client like this :
private async Task<ChannelFactory<T>> CreateChannelFactory(LoginTypeBase loginType, MyappToken token)
{
var service = await _ConsulService.GetServiceBlocking(loginType.MyappServicesToUse, forceRefresh: true, token: new CancellationTokenSource(TimeSpan.FromSeconds(30)).Token);
if (service == null)
throw new MyappServiceCommunicationException();
var cert = loginType.ClientCertificate;
var uri = loginType.GetMyappClientServiceURL(service.Address, service.Port);
var header = AddressHeader.CreateAddressHeader(nameof(MyappToken), nameof(MyappToken), token);
var endpointAddress = new EndpointAddress(uri, header);
ServiceEndpoint serviceEndpoint = null;
if (loginType.LoginType == LoginType.SmartCard || loginType.LoginType == LoginType.UsernamePasswordSLL)
{
var binding = new NetHttpsBinding("netHttpsBinding");
binding.Security.Mode = BasicHttpsSecurityMode.Transport;
if (loginType.LoginType == LoginType.SmartCard)
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
else
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), binding, endpointAddress);
}
else
{
var binding = new NetHttpBinding("netHttpBinding");
serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), binding, endpointAddress);
}
serviceEndpoint.EndpointBehaviors.Add(new ProtoEndpointBehavior());
serviceEndpoint.EndpointBehaviors.Add(new CustomMessageInspectorBehavior());
var v = new ChannelFactory<T>(serviceEndpoint);
if (loginType.LoginType == LoginType.SmartCard)
{
v.Credentials.ClientCertificate.Certificate = cert;
//v.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, cert.Thumbprint);
}
return v;
}
The config contains extensions, behaviours and bindings(netHttpsBinding).
The Service is created from code only, nothing from its config file.
Why does it not work on the other computer?
Whenever I try to run this code: (code shortened to keep the post short)
// Generate a random capital letter
char key = (char)(_random.Next(24) + 65);
// 50% make it lowercase
if (_random.Next(2) == 0)
{
key = Char.ToLower(key);
}
SendKeys.SendWait(key.ToString());
I get this error:
Unhandled Exception: System.ComponentModel.Win32Exception: The operation completed successfully
at System.Windows.Forms.SendKeys.SendInput(Byte[] oldKeyboardState, Queue previousEvents)
at System.Windows.Forms.SendKeys.Send(String keys, Control control, Boolean wait)
at System.Windows.Forms.SendKeys.SendWait(String keys)
at DrunkPC.Program.DrunkKeyboardThread() in c:\Users\SPC\Documents\Visual Studio 2013\Projects\DrunkPC\Program.cs:line 91
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Line 91 is:
SendKeys.SendWait(key.toString());
I've noticed that when I'm using System.Net.HttpClient with a short timeout, it may sometimes crash the process, even when it is wrapped in a try-catch block. Here's a short program to reproduce this.
public static void Main(string[] args)
{
var tasks = new List<Task>();
for (int i = 0; i < 1000; i++)
{
tasks.Add(MakeHttpClientRequest());
}
Task.WaitAll(tasks.ToArray());
}
private async static Task MakeHttpClientRequest()
{
var httpClient = new HttpClient { Timeout = TimeSpan.FromMilliseconds(1) };
var request = "whatever";
try
{
HttpResponseMessage result =
await httpClient.PostAsync("http://www.flickr.com/services/rest/?method=flickr.test.echo&format=json&api_key=766c0ac7802d55314fa980727f747710",
new StringContent(request));
await result.Content.ReadAsStringAsync();
}
catch (Exception x)
{
Console.WriteLine("Error occurred but it is swallowed: " + x);
}
}
Running this will crash the process with the following exception:
Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.Net.WebException: The request was canceled
at System.Net.ServicePointManager.FindServicePoint(Uri address, IWebProxy proxy, ProxyChain& chain, HttpAbortDelegate& abortDelegate, Int32& abortState)
at System.Net.HttpWebRequest.FindServicePoint(Boolean forceFind)
at System.Net.HttpWebRequest.get_ServicePoint()
at System.Net.AuthenticationState.PrepareState(HttpWebRequest httpWebRequest)
at System.Net.AuthenticationState.ClearSession(HttpWebRequest httpWebRequest)
at System.Net.HttpWebRequest.ClearAuthenticatedConnectionResources()
at System.Net.HttpWebRequest.Abort(Exception exception, Int32 abortState)
at System.Net.HttpWebRequest.Abort()
at System.Net.Http.HttpClientHandler.OnCancel(Object state)
at System.Threading.CancellationCallbackInfo.ExecutionContextCallback(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.CancellationCallbackInfo.ExecuteCallback()
at System.Threading.CancellationTokenSource.CancellationCallbackCoreWork(CancellationCallbackCoreWorkArguments args)
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
--- End of inner exception stack trace ---
at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
at System.Threading.CancellationTokenSource.NotifyCancellation(Boolean throwOnFirstException)
at System.Threading.CancellationTokenSource.TimerCallbackLogic(Object obj)
at System.Threading.TimerQueueTimer.CallCallbackInContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.TimerQueueTimer.CallCallback()
at System.Threading.TimerQueueTimer.Fire()
at System.Threading.TimerQueue.FireNextTimers()
at System.Threading.TimerQueue.AppDomainTimerCallback()
Digging in a little, it seems that when HttpClient aborts the request before a relevant ServicePoint is created, HttpWebRequest attempts to create the ServicePoint, via ServicePointManager.FindServicePoint, which throws a RequestCanceled. Since this exception is thrown in the thread that attempts to cancel the request, it is not caught, and the process dies.
Am I missing something? Have you run into this issue?
HttpWebRequest.Abort() is throwing an exception on a background/timer thread. This has nothing to do with HttpClient's Task management.
The exception from HttpWebRequest.Abort() should be fixed in .NET 4.5 GDR1.
http://support.microsoft.com/kb/2750149
http://support.microsoft.com/kb/2750147
Looks like it's some kind of bug in how the async handler for HttpClient is managing the tasks. I was able to launch the items in parallel, but run them synchronously and it works. I'm not sure if you want to just prevent the unhandled error or not. This ran parallel tasks, but they aren't async really since I turned it off. On my computer I would always get to 5 rounds and it would crash. Even if i set it to timeout after a second, it's like the crashes in the threads would still blow up if they were async.
I think it's a bug, I can't imagine this is intended behavior.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestCrash
{
class Program
{
static void Main(string[] args)
{
try
{
Parallel.ForEach(Enumerable.Range(1, 1000).ToList(), i =>
{
Console.WriteLine(i);
using (var c = new HttpClient { Timeout = TimeSpan.FromMilliseconds(1) })
{
var t = c.GetAsync("http://microsoft.com");
t.RunSynchronously(); //<--comment this line and it crashes
Console.WriteLine(t.Result);
}
});
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
Console.ReadKey();
}
}
}