Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with WebSockets in Flutter

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.

like image 460
DrkStr Avatar asked Nov 16 '25 07:11

DrkStr


1 Answers

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.

like image 169
DrkStr Avatar answered Nov 17 '25 21:11

DrkStr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!