Robert
Robert

Reputation: 5855

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.

Upvotes: 8

Views: 16079

Answers (6)

Googlian
Googlian

Reputation: 6703

There is no official Socket.IO release for Flutter however, the implementation is still possible by one of the best Dart libraries called adhara_socket_io which is developed according to the Socket.IO Java client and Swift. It supports Android and iOS.

Implementation

SocketIOManager manager = SocketIOManager();

SocketIO socket = manager.createInstance(SocketOptions(
    'http://192.168.1.12:5555',
    nameSpace: '/yournamespace',
    enableLogging: true,
    transports: [Transports.POLLING]
));

socket.onConnect((data) {
  print("onConnected");
  print(data);
});

socket.on("news", (data) {
  print("onNews");
  print(data);
});

socket.connect();

Emit

socket.emit("some_event", ["Hello world!"]);

Documentation: GitHub | Dart

Before implement, the library, refer to the latest version always. Releases

Upvotes: 1

Luis Ciber
Luis Ciber

Reputation: 300

adhara_socket_io

dependencies:
adhara_socket_io: ^0.1.11

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

Upvotes: 3

Tim Bull
Tim Bull

Reputation: 2495

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.

Upvotes: 3

Alexey Semigradsky
Alexey Semigradsky

Reputation: 51

Regular Dart packages not suitable for the Flutter, so I created a package, but currently, it only works on the Android devices. Check it out: https://github.com/AlexeySemigradsky/socket_io

Example of usage:

const uri = 'http://192.168.1.38:8080';
final socket = await SocketIO.createNewInstance(uri);
await socket.on(SocketIOEvent.connecting, () async {
  print('Connecting...');
});
await socket.on(SocketIOEvent.connect, () async {
  print('Connected.');

  final id = await socket.id;
  print('Client SocketID: $id');
});
await socket.on(SocketIOEvent.connectError, (error) {
  print('Error: $error');
});
await socket.on('sayHello', (greeting) {
  print('Hello, ${greeting['Hello']}');
});
await socket.connect();
await socket.emit('sayHello', [
  {'Hello': 'world!'},
]);

Upvotes: 2

Robert
Robert

Reputation: 5855

I found how to make this work efficiently. I am using

import 'package:web_socket_channel/io.dart';

This give the needed code to connect, sed and receive messages.

doConnect(url, fullname) async {
    chatsocket = await new IOWebSocketChannel.connect(url, pingInterval: new Duration(seconds: 5));
    ChatServerConnect csc =  new ChatServerConnect('connect', fullname);
    var json = jsonCodec.encode(csc);
    chatsocket.sink.add(json);
    _getPrefs();
    isConnected = true;
    syncMessages();
    chatlisten(chatsocket);
  }

This can be modified to connect however you need to, this is specific to a websocket server I created.

Hope this helps. Do not forget you need a listener as well for incoming messages, I did this as a singleton and declaring an instance so that it can be called from the entire app.

Upvotes: -3

BauerMitFackel
BauerMitFackel

Reputation: 372

I also recently tried to connect a Flutter App to a socket.io service.

Unfortunately you can not simply use WebSocket without implementing the socket.io protocol. Because i do not want to implement this by myself i tried to find a socket.io library for Dart. There is a library (https://github.com/rikulo/socket.io-dart) but it is not working in flutter because it uses dart html. Until now, i have not found a good solution to this problem.

Regards

Upvotes: 2

Related Questions