Trouble with WebSockets in Flutter
Turns out you channel.sink.add
accepts a string and not a Map.
Replace
channel.sink.add({"action": "saveConnection","UserName": "rakshak@gmail.com","DeviceId": "1d0032000947363339343638"});
With
channel.sink.add('{"action": "saveConnection","UserName": "rakshak@gmail.com","DeviceId": "1d0032000947363339343638"}');
and it should work.
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();
I don't understand what you want. But If you want websocket, you can refer below one.
Add Dart Pub
adhara_socket_io
Add class
class SignalServer { static SignalServer _instatnce; factory SignalServer() => _instatnce ?? new SignalServer._(); SignalServer._(); SocketIO socketIO; int State = 0; void ConnectServer() async { this.socketIO = await SocketIOManager().createInstance("http://192.168.50.65:8081"); socketIO.onConnect((data) { print("Signal server connected"); State = 1; }); socketIO.onDisconnect((_) { print("Signal Disconnected"); State = 0; }); socketIO.connect(); }}
For Instance(main.dart)
static SignalServer signalServer;....signalServer = new SignalServer();signalServer.ConnectServer();
For use
In any widget
void initState() { super.initState(); setSocketEvent(); } void setSocketEvent() async{ await MyApp.signalServer.socketIO.on("room-ready", (data) { //enter your code }); await MyApp.signalServer.socketIO.on("on-message", (data) { //enter your code }); ... }
I hope it will help you.