Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter WebSockets connect to Socket.io Server

I have built a socket.io server using Node.js and Express. All works fine from browser and normal socket.io client but when I try to use WebSocket in Flutter I get the error

HttpException: Connection closed before full header was received, uri = http://csw.abbadabba.tech:3001

I am just trying to get it to work with a basic connect like this:

var _url = 'ws://csw.abbadabba.tech:3001';
WebSocket chatsocket = await WebSocket.connect(_url);
chatsocket.add('connect');

Looking for anyone who has done this already and has some samples to look at, trying to have a chat server that my app is always connected to, so if there is a better server architecture to use I am open to that as well. Any help would be great.

Thanks in advance.

like image 516
Robert Avatar asked Dec 29 '17 13:12

Robert


People also ask

Can WebSocket connect to socket IO?

Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.

How do you connect socket IO in Flutter?

It's super simple, start a connection, then listen with client. on , next, pass in an event to listen to e.g “message” and emit (send) the data received right away back to everyone listening to the server. Your WebSocket should be running at http://localhost:3000 .

Does Flutter support socket IO?

Usage (Flutter) not (Flutter Web env.) it only works with dart:io websocket, not with dart:html websocket or Ajax (XHR), so in this case you have to add setTransports(['websocket']) when creates the socket instance.


2 Answers

The problem is that you are trying to use Flutter's WebSocket implementation to connect to a socket.io server. Although socket.io does use WebSockets, it is NOT a pure web socket implementation and isn't recognized by default WebSocket client as valid. You'll need to use a specific socket.io flutter package.

From the socket.io documentation: https://socket.io/docs/#What-Socket-IO-is-not

What socket.io is not

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket as a transport when possible, it adds some metadata to each packet: the packet type, the namespace and the ack id when a message acknowledgement is needed. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server either.

like image 185
Tim Bull Avatar answered Sep 20 '22 13:09

Tim Bull


adhara_socket_io

dependencies:
adhara_socket_io: ^0.1.11

This is good implementation of socket.io for flutter ->

like image 21
Luis Ciber Avatar answered Sep 20 '22 13:09

Luis Ciber