尝试在Flutter中读取数据时,NodeJS Socket不发出通道

时间:2019-06-12 07:48:56

标签: node.js flutter socket.io

我试图在后端使用Flutter和Nodejs和Socket实现聊天应用程序,但是当套接字连接初始化时,我能够发出数据,但是当我尝试通过http发送数据并响应套接字发出时。它不起作用。

//Flutter Code
socket =
        await manager.createInstance(socketUrl, query: {}, enableLogging: true);
socket.onConnect((data) {
  print("Connected $data");
  socket.emit("message", ['World']);
});
socket.on('chatMessage', (data) {
  print("Hello $data");
});
socket.onConnectError(pprint);
socket.onConnectTimeout(pprint);
socket.onError(pprint);
socket.onDisconnect(pprint);
socket.connect();

//NodeJS
io.on('connection', (client) => {
  client.on('message', function(data) {
    console.log(data);
    io.emit('chatMessage', data);
  });
  client.on('disconnect', () => {
    console.log('disconnected');
  });
  client.on('error', (error) => {
    console.log(error);
  });
});

//When Sending data via HTTP
Controller
const io = require('../app');
module.exports.sendMessage = async (req, res, next) => {  
  try {
    //Business Logic
    io.emit('chatMessage', message);
    return res.status(200).send({
        success: true,
        foundChat: message,
    });
  } catch (error) {
    return res.status(200).send({
      success: false,
      message: 'syntex error',
      error: error.message,
    });
  }
};

io.emit('chatMessage',message);不会在Flutter中发射数据

0 个答案:

没有答案