locked
关于StreamSocketListener的疑问。

    Question

  • 错误信息:

    First-chance exception at 0x77B34B32 in StreamSocketDemo.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x031FC7AC. HRESULT:0x8000000E

    代码:

    void StreamSocketDemo::MainPage::start_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)

    {

    StreamSocketListener^ listen = ref new StreamSocketListener();

    task<void>(listen->BindServiceNameAsync(port->Text)).then([this,&listen](task<void> previousTask) {

    try {

    previousTask.get();

    }

    catch(Exception^ ex) {

    String^ error = ex->Message;

    msg->Text = error;

    }

    listen->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &StreamSocketDemo::MainPage::OnConnection);

    });

    }

    void StreamSocketDemo::MainPage::OnConnection(StreamSocketListener^ listener, StreamSocketListenerConnectionReceivedEventArgs^ object){

    msg->Text = "LoadData";

    }


    为什么吧OnConnection 设置为回调函数会出问题呢?

    Tuesday, October 16, 2012 8:29 AM

Answers

  • Eric_00101

    You should set ConnectionReceived event before calling the BindServiceNameAsync. After calling the BindServiceNameAsync, the binded port is ready to receive any connection.

    So, first assign the ConnectionReceived event to the listener

    listen->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &StreamSocketDemo::MainPage::OnConnection);
    
    });

     and then call BindServiceNameAsync for binding

    task<void>(listen->BindServiceNameAsync(port->Text)).then([this,&listen](task<void> previousTask) {
    
    try {
    
    previousTask.get();
    
    }
    
    catch(Exception^ ex) {
    
    String^ error = ex->Message;
    
    msg->Text = error;
    
    }


    Please see the following reference for maintaining the proper order of operations.

    StreamSocketListener class

    • Marked as answer by Eric_00101 Wednesday, October 17, 2012 2:22 AM
    Tuesday, October 16, 2012 1:21 PM