Silverlight's Socket.ConnectAsync method never calls the Completed event - I am using 127.0.0.1:4510 . I have configured IIS to serve clientaccesspolicy.xml file on port 943.
I am using following code:
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
//args.UserToken = tcp;
args.RemoteEndPoint = ep;
args.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
mrEvent.Reset();
bool x = tcp.ConnectAsync(args);
mrEvent.WaitOne();
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
isConnected = (e.SocketError == SocketError.Success);
开发者_JAVA技巧 mrEvent.Set();
}
The OnConnect method is never called and as a result the code blocks due to the WaitOne method.
Note: This code is being executing on a background thread so there is no deadlock due to the WaitOne call.
I had a similar issue I just resolved; I saw your post when I was looking for answers and thought I'd best share, even though it's an old post. Even if you're long past this issue, others will find this post.
I thought my event handler wasn't firing, too. Turns out it WAS, but it was firing on a background thread and couldn't affect the user interface. The solution was to make sure that the handler fired on the user interface thread. Use CheckAccess and, if it's not on the main thread, send it there using Dispatcher.BeginInvoke.
Hope this helps!
Silverlight async socket API (the only one available) is very bad.
In your case, if the value, returned from ConnectAsync
is false
, the call was made synchronous and the OnConnect
method was not called.
Here is the synchronous version of the ConnectAsync
:
public static bool Connect(this Socket socket, EndPoint remoteAddress) {
ManualResetEvent semaphore = new ManualResetEvent(false);
SocketAsyncEventArgs socketEventArgs = new SocketAsyncEventArgs() {
RemoteEndPoint = remoteAddress
};
socketEventArg.SetBuffer(buffer, 0, buffer.Length);
socketEventArg.Completed += (s, e) => {
semaphore.Set();
};
semaphore.Reset();
bool wasAsynchronous = socket.ConnectAsync(socketEventArgs);
if (wasAsynchronous) {
semaphore.WaitOne();
}
return socketEventArgs.SocketError == SocketError.Success;
}
精彩评论