Shreyansh Sharma
Shreyansh Sharma

Reputation: 1824

socket.io is not working and my flutter app is not being connected to server or backend part

I used socket.io and node.js for my backend part in my flutter app. I made a file index.json and made a function in a page to connect my app to backend. But it doesn't work. Here is the function, which i called in initstate -

void connect() {
    socket = IO.io("http://my ip address", <String, dynamic>{
      "transports":["websocket"],
      "autoConnect":false,
    });
    socket.connect();
    socket.onConnect((data) => print("Connected"));
    print(socket.connected);
    socket.emit("/test", "Hello World");
  }
  


    @override
  void initState() {
    // TODO: implement initState
    super.initState();
    connect();
    //Some other code
  }  

Here is index.js file -

const express = require("express");
var http = require("http");
 const cors = require("cors");
 const app = express();
 const port = process.env.PORT || 5000;
 var server = http.createServer(app);
 var io = require("socket.io")(server, {
     cors:
     {
        origin:"*"
     }
 });

 //middlewre
 app.use(express.json());
 app.use(cors());

 io.on("connection", (socket)=>{
    console.log("connected");
    console.log(socket.id, " has joined");
    socket.on("/test", (msg)=>{
       console.log(msg);
    });
 });

 server.listen(port,"0.0.0.0",()=> {
    console.log("server started");
 })

In run log, it is showing/printing false only

Upvotes: 3

Views: 2747

Answers (1)

J. S.
J. S.

Reputation: 9625

As it seems you are testing with an Android emulator, you can't use 127.0.0.1 to connect to your localhost, you need to use the address 10.0.2.2.

You will also need to use the ws:// protocol instead of http://.

You can find the official documentation here: https://developer.android.com/studio/run/emulator-networking

Upvotes: 5

Related Questions