Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with real device and socket.io in Flutter

i have this issue when i tried to run my app in a physical device in debug mode. When I try to debug the next code:

class SocketService with ChangeNotifier {
  ServerStatus _serverStatus = ServerStatus.Connecting;
  SocketService() {
    this._initConfig();
  }
  void _initConfig() async {
    IO.Socket socket = IO.io('http://192.168.56.1:3000/', <String, dynamic>{
      'transports': ['websocket'],
      'autoConnect': true,
    });

    socket.on('connect', (_) {
      print('connect');
    });
    socket.on('event', (data) => print(data));
    socket.on('disconnect', (_) => print('disconnect'));
    socket.on('fromServer', (_) => print(_));
  }
}

And in my backend i have this:

file index.js

const express = require('express');
const path = require('path');
require('dotenv').config();

const app = express();

const server = require('http').createServer(app);
module.exports.io = require('socket.io')(server);
require('./sockets/socket');

const publicPath = path.resolve( __dirname, 'public' );
app.use( express.static( publicPath ) );

server.listen( process.env.PORT, ( err ) => {

    if ( err ) throw new Error(err);
    console.log('Servidor corriendo en puerto', process.env.PORT );

});

file socket.js

const { io } = require('../index');

io.on('connection', client => {
    console.log('Cliente conectado');
    client.on('disconnect', () => {
        console.log('Cliente desconectado');
    });
    client.on('mensaje', ( payload ) => {
        console.log('Mensaje', payload);
        io.emit( 'mensaje', { admin: 'Nuevo mensaje' } );
    });
});

In web works good and print's the 'disconnect' adn the 'connect' perfectly, but when i tried to debug in my cellphone, nothings happends, i don't get any message from the socket instance, if anyone knows how to solved this I would appreciate.

like image 860
Johan David Avatar asked Feb 16 '26 00:02

Johan David


1 Answers

I figure out what was the problem, was with the AndroidManifest The way I solved was with the next code

In the <application> I add this line android:usesCleartextTraffic="true"

The result was this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.band_names">
   <uses-permission android:name="android.permission.INTERNET"/>
   <application
        android:label="band_names"
        android:icon="@mipmap/ic_launcher"
        android:usesCleartextTraffic="true">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>
like image 75
Johan David Avatar answered Feb 18 '26 16:02

Johan David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!