Ad

Connecting Flutter To The A Local Nodejs Socket Server

- 1 answer

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.

Ad

Answer

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/

Ad
source: stackoverflow.com
Ad