UWP C# .net StreamSocket with User Token in HostName

278 views Asked by At

Is there a way to format the HostName for a StreamSocket to include a user token? I get a "Parameter is Incorrect" exceptions when I try to use a URI with the a user Token. I have had success with a MessageWebSocket but I need a StreamSocket because it is able to (easily) run in the background on Windows 10 UWP. Here is my code. Any help would be greatly appreciated.

public static async void ConnectToStreamSocket()
    {
        StreamSocket socket = new StreamSocket();
        string hostUri = "//example.myexample.com/websocket/dfkjlkdfskldklfdkddkfdkffjf";
        HostName host = new HostName(hostUri);           
        string proto = "wss";
        await socket.ConnectAsync(host, proto);
    }
1

There are 1 answers

2
Sunteen Wu On BEST ANSWER

I get a "Parameter is Incorrect" exceptions when I try to use a URI with the a user Token.

The parameter of HostName constructor is not a URI, but a string that contains a hostname or an IP address. According to the description of the hostName parameter, it can contain one of the following:

  • The name of a host that can be resolved by the Domain Name System (DNS) or by another namespace provider.
  • The name of a host that matches a string in the following file on the local computer: %WINDIR%\system32\drivers\etc\hosts
  • A string that contains an IPv4 or an IPv6 network address of the host.

For "//example.myexample.com/websocket/dfkjlkdfskldklfdkddkfdkffjf", this is a URI that don't meet above requirements so that the it cannot be recognized by HostName class. Value like example.myexample.com can be recognized.

For why you can successfully use MessageWebSocket class, this is because MessageWebSocket.ConnectAsync method requires a URI parameter as you provided.

but I need a StreamSocket because it is able to (easily) run in the background on Windows 10 UWP.

WebSockets provide a mechanism for fast, secure two-way communication between a client and a server over the web using HTTP(S). Socket can be used for communicating with other device. They are not the same things, we cannot simply transfer WebSockets to StreamSocket. More details about WebSockets and StreamSockets in uwp please reference the official documents Sockets and WebSockets.

But WebSockets can be used in background, you may not need StreamSocket. If you are using WebSockets in background, you must use ControlChannelTrigger. Details for how to use WebSockets with ControlChannelTrigger please reference ControlChannelTrigger with WebSockets.