isa türk
isa türk

Reputation: 747

Connecting Flutter to the a local nodejs socket server

I am developing a chat part form my app and I coded a basic socket server with node js and socket.io.

I tested this API with this site: https://www.websocket.org/echo.html

Here is some source code :

  var server = require('http').Server(app)
  var io = require('socket.io')(server);

  app.use(bodyParser.urlencoded({
    extended: true,
    limit: '50mb',
  })); 
  app.use(bodyParser.json());
  app.use("/f",express.static(__dirname+"/files"));
  app.use('/api', listenRoutes);


  io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
      console.log('user disconnected');
    });
  });

  server.listen(port);


  console.log('Bukalemun RESTful API server started on: ' + port);

My API is served on http://localhost:3000

However I am having trouble connecting this API to my flutter app. I used various types of packages including original dart.io but I never succeeded.

This is the function to connect my API:

import 'dart:io';

  void setupSocketConnections() async {

    Socket socket = await Socket.connect('10.0.2.2', 3000);

    print('connected');

    // listen to the received data event stream
    socket.listen((List<int> event) {
      print(utf8.decode(event));
    });

    // send hello
    socket.add(utf8.encode('hello'));

    // wait 5 seconds
    await Future.delayed(Duration(seconds: 5));

    // .. and close the socket
    socket.close();

  } 

I would be grateful for any suggestions.

Upvotes: 1

Views: 4922

Answers (2)

neon97
neon97

Reputation: 660

Try using this mostly you might have used some headers with the sockets as .

'transports': ['websocket', 'polling']

Use this dependency in your pubspec.yaml

[socket_io_client: ^0.9.7+2][1]

Well use this code to connect in your flutter app.

connectToSocket() {
socket = IO.io("http://your url/", <String, dynamic>{
  'transports': ['websocket', 'polling'],
});
socket.connect();

}

Hope it works for you ! It has worked for me.

Upvotes: 2

isa t&#252;rk
isa t&#252;rk

Reputation: 747

I suppose this was a localhost related error. The problem resolved when I deployed my server to heroku and connected it via this library https://pub.dev/packages/adhara_socket_io#-readme-tab-

I shared my basic client example here : https://github.com/isaturk66/dart_socket_client_example

Server side is a basic socket.io server there is already documentation on their official site : https://socket.io/docs/

Upvotes: 1

Related Questions