locked
StreamSocketListenerInformation.LocalPort is empty after BindEndpointAsync

    Question

  • StreamSocketListenerInformation.LocalPort is empty after BindEndpointAsync

    _listener = ref new StreamSocketListener();
    _listener->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(
               [=](StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^ args)
                   {
                       this->accept(args->Socket);
                   });
    concurrency::task<void> t(_listener->BindEndpointAsync(ref new HostName(ref new String(L"localhost")), ref new String(L"10010")));
    t.then([this] (concurrency::task<void> prev)
       {
                   try
                   {
                           prev.get();
                   }
                   catch(Platform::Exception^ ex)
                   {
                           print(ex->Message->Data());
                   }
       });
    std::wstring s =(_listener->Information->LocalPort->Data());
    assert(!s.empty()); // Fails 
    I will expect s == 10010


    Monday, June 4, 2012 7:40 PM

Answers

  • your assert is happening before the BindEndpointAsync completes. It's an asynchronous operation. If you put the failing codeinside the continuation (the .then(...)) you'll get the behavior you're looking for:

    	auto _listener = ref new StreamSocketListener();
    	_listener->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^,StreamSocketListenerConnectionReceivedEventArgs^>(
    		[=](StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^ args)
            {
                this->accept(args->Socket);
            });
    
    	concurrency::task<void> t(_listener->BindEndpointAsync(ref new HostName(ref new String(L"localhost")), ref new String(L"10010")));
    	t.then([this, _listener] (concurrency::task<void> prev)
    	{
    		std::wstring s =(_listener->Information->LocalPort->Data());
    		assert(!s.empty());
    		try
    		{
    			prev.get();
    		}
    		catch(Platform::Exception^ ex)
    		{
    			print(ex->Message->Data());
    		}
    	});
    

    • Marked as answer by pepone.onrez Monday, June 4, 2012 10:30 PM
    Monday, June 4, 2012 10:03 PM
    Moderator