【问题标题】:Socket.connected returning false with Flutter Socket.io_client, connected to Node.js Socket.io serverSocket.connected 使用 Flutter 返回 false Socket.io_client,连接到 Node.js Socket.io 服务器
【发布时间】:2022-01-20 04:19:49
【问题描述】:

我正在尝试将我的 Flutter 应用程序连接到运行 Socket.io 的 Node.js 服务器。但是,每当我打印出 socket.connected 时,它都会返回 false。

我的 Flutter Socket.io_client 版本是socket_io_client: ^2.0.0-beta.4-nullsafety.0,我的 Node.js socket.io 版本是 3.1.2。这意味着没有由于版本不兼容而导致的错误。

如何让 Flutter 客户端连接到我的 Node 服务器?

这是我连接到节点服务器的代码。

  void initState() {
    
    super.initState();
    connect();
  }

  void connect(){
    print("ASDASD");
    IO.Socket socket = IO.io("https://geobus-server.ibrahimshah.repl.co/", <String, dynamic>{
      'transports':['websocket'],
      'autoConnect': true,
    });
    socket.connect();
    socket.onConnect((data) => print("Connected"));
    print(socket.connected);
    
  }

这是我的 Node.js 服务器代码:

const app = express();
const http = require("http");
const server = http.createServer(app);
var io = require('socket.io')(server);

app.get('/', (req, res) => {
  res.send('Hello Express app!')
});


app.get('/questions', (req, res)=>{
  console.log(req.url);
  

})

io.on('connection', (socket) => {
    
    console.log("User connected")
    
});

app.listen(3000, () => {
  console.log('server started');
});

我的输出: false

【问题讨论】:

    标签: node.js flutter sockets dart socket.io-1.0


    【解决方案1】:

    print 行放在socket.onConnect 方法块中,然后再次检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 2018-10-06
      • 2011-06-11
      • 2021-11-18
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多