Trouble with WebSockets in Flutter

3,161

Solution 1

Turns out you channel.sink.add accepts a string and not a Map.

Replace

channel.sink.add({
"action": "saveConnection",
"UserName": "[email protected]",
"DeviceId": "1d0032000947363339343638"
});

With

channel.sink.add('{
"action": "saveConnection",
"UserName": "[email protected]",
"DeviceId": "1d0032000947363339343638"
}');

and it should work.

Solution 2

The web_socket_channel package has tools that are needed to connect to a WebSocket server. The package provides a WebSocketChannel that allows users to both listen to messages from the server and push messages to the server.

Use the following line to create a WebSocketChannel that connects to a server:

var channel = IOWebSocketChannel.connect("ws://localhost:1234");

Listen to messages from the server:

StreamBuilder( 
  stream: widget.channel.stream, 
  builder: (context, snapshot) { 
    return Text(snapshot.hasData ? '${snapshot.data}' : ''); 
  }, 
); 

Send Data to the Server:

To send data to the server, add() messages to the sink provided by the WebSocketChannel as shown below:

channel.sink.add('connected!');

Close the Connection: To close the connection to the WebSocket use the below:

channel.sink.close();
Share:
3,161
DrkStr
Author by

DrkStr

Jack of many trades.

Updated on December 14, 2022

Comments

  • DrkStr
    DrkStr over 1 year

    I am having some trouble implementing WebSockets in my flutter application.

    Here is code my code:

    void connectToWebSocket() {
    print("trying to connect to websocket");
    
    final Future futureChannel = establishConnection();
    futureChannel.then((future) {
      print("Connection established, registering interest now...");
      channel = future;
      webSocketConnected = true;
      channel.sink.add({
        "action": "saveConnection",
        "UserName": "[email protected]",
        "DeviceId": "1d0032000947363339343638"
      });
    }).catchError((error) {
      channel = null;
      webSocketConnected = false;
      webSocketConnectionError = error.toString();
      print("Connection failed \n $webSocketConnectionError");
    });
    }
    
    Future<IOWebSocketChannel> establishConnection() async {
    final IOWebSocketChannel channel = IOWebSocketChannel.connect(
        'wss://1j839fy6t3.execute-api.us-east-1.amazonaws.com/Dev');
    
    return channel;
    }
    

    Nothing seems to happen when this code runs. I can see the print messages saying "trying to connect to WebSocket" and "Connection established, registering interest now..." on the console.

    The WebSocket is implemented using AWS API Gateway and I can see in the logs that the Flutter app has not connected to the WebSocket.

    I have tested the WebSocket using wscat command-line tool and I know that it works.

    wscat command line tool

    I am not seeing any error in the console.

    Let me know if you would like to see any more of my code.