Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dart:io WebSocket with wss:// protocol (SSL)

I tried to use the WebSocket class in the dart:io package to connect to an SSL WebSocket service. This doesn't seem to work. Isn't the wss:// protocol supported at the moment or am I missing something. Here is the code used:

var ws = new WebSocket('wss://...');

ws.onopen = () {
    print('open');
};

ws.onmessage = (e) {
    print(e.data);
};

I also tried the alternative API:

var client = new HttpClient(),
    conn = new WebSocketClientConnection(client.getUrl(new Uri.fromString('https://...')));

    conn.onMessage = (msg) {
        print(msg);
    };

    conn.onOpen = () {
        print('open');
    };

This doesn't seem to work either, I get errors like:

1006 HttpParserException: Connection closed before full response header was received 1006 HttpParserException: Invalid request method

I am using the latest SDK.

like image 614
gmosx Avatar asked May 20 '26 16:05

gmosx


1 Answers

I am assuming that you are the latest version of Dart. I would recommend updating if you are not.

Some of the methods you are calling - conn.onMessage(), conn.onOpen() return Stream objects and you need to use a .listen() to access ('listen to') the stream. Here is the syntax:

import 'dart:html';

void main() {
  var wss = new WebSocket('wss://echo.websocket.org');
  wss.onOpen.listen((item) {
    wss.send("hello world");
  });

  wss.onMessage.listen((message) {
    print(message.data);
  });
}

etc.

Can you try that? For more details, read about Stream and Websocket in the api docs.

like image 56
Shailen Tuli Avatar answered May 22 '26 06:05

Shailen Tuli