Thank you @Viorel , that works. When visual studio intercepted the error (thought it was a fatal exception) I ticked the dialog in the alert window as you said and it doesn't 'crash' any more. Here's the working code:
//.xaml
<ListBox x:Name="clientListBox">
//.h
bool connected{ false };
bool closing { false };
Windows::Networking::Sockets::StreamSocket m_streamSocket;
hstring socketAddress = L"1337";
Windows::Networking::HostName hostName{ L"192.168.86.48" };
Windows::Foundation::IAsyncAction OpenSocket();
//.cpp
using namespace Windows::Networking::Sockets;
Windows::Foundation::IAsyncAction MainPage::OpenSocket() {
if (connected) {
clientListBox().Items().Append(winrt::box_value(L"already connected"));
return;
}
try
{
clientListBox().Items().Append(winrt::box_value(L"client is trying to connect..."));
co_await m_streamSocket.ConnectAsync(hostName, socketAddress);
connected = true;
clientListBox().Items().Append(winrt::box_value(L"client connected"));
}
catch (winrt::hresult_error const& ex)
{
SocketErrorStatus errorStatus = SocketError::GetStatus(ex.to_abi());
connected = false;
closing = true;
//no dispose in c++winrt?
m_streamSocket = nullptr;
std::wstringstream wstringstream;
//full list here: https://learn.microsoft.com/en-us/uwp/api/windows.networking.sockets.socketerrorstatus
if (errorStatus == SocketErrorStatus::ConnectionTimedOut) {
clientListBox().Items().Append(winrt::box_value(L"Computer at - " + hostName.RawName() + L": " + socketAddress + L" timed out.\nCheck it is trying to connect."));
wstringstream << L"A connection attempt failed.";
::OutputDebugString(wstringstream.str().c_str());
}
else if (errorStatus == SocketErrorStatus::ConnectionRefused) {
//WinRT originate error - 0x8007274D : 'No connection could be made because the target machine actively refused it.'.
clientListBox().Items().Append(winrt::box_value(L"Other computer refused connection - \nCheck IP: " + hostName.RawName() + L"\nCheck socket: " + socketAddress));
wstringstream << L"Connection actively refused.\n";
::OutputDebugString(wstringstream.str().c_str());
}
else {
auto msg = (errorStatus != SocketErrorStatus::Unknown) ? winrt::to_hstring((int32_t)errorStatus) : winrt::to_hstring(ex.to_abi());
wstringstream << L"webErrorStatus: " << msg;
::OutputDebugString(wstringstream.str().c_str());
}
}
}