【问题标题】:Unable to connect to socket IO locally in reactjs?无法在reactjs中本地连接到套接字IO?
【发布时间】:2019-03-24 08:46:13
【问题描述】:

我使用 nodeJs 作为后端,reactJs 作为我的前端,问题是我从节点发出了一个套接字发出函数

var server = require('http').createServer();
var io = require('socket.io')(server);
io.emit('quantity_check', 'KR')

现在的问题是我无法捕捉到发射

let serverUrl = 'localhost:3008'
const socket = socketIOClient(serverUrl);
socket.on("quantity_check", data => this.setState({ kiiii: data }));`  
const socket = socketIOClient(serverUrl);

我正在本地检查这个,即使我尝试使用我的 ip 它没有连接我不确定问题发生在哪里 pc:nodejs 和 reactjs 在不同的端口上运行

【问题讨论】:

  • 你试过http://localhost:3008吗?你是如何在 FE 中导入你的套接字库的?
  • 从“socket.io-client”导入socketIOClient;你试过了,但没有在控制台中工作,只有断开连接才是真实的

标签: node.js reactjs socket.io


【解决方案1】:

你能发布你的节点服务器文件的代码和你在哪里监听套接字的反应文件吗?无论如何,我希望发出事件是在connection

io.on('connection', function(socket) {
  io.emit('quantity_check', 'KR')
}

你有没有使用生命周期方法componentDidMount来接收消息

  componentDidMount() {
    socket.on("quantity_check", data => {
      console.log(data);
    });
  }

试试这样的。

服务器

const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connect', (socket) => {
  io.emit('quantity_check', 'KR');
});

客户端(反应端)

import io from 'socket.io-client';
const socket = io('http://localhost:3008');
export class App extends Component {

 componentDidMount() {
   socket.on('connect', () => {
    console.log(socket.connected); 
   });
   socket.on("quantity_checke", data => {
            console.log(data);
     });
 }
   render().......
 }

【讨论】:

  • var server = require('http').createServer(); var io = require('socket.io')(server); io.emit('quantity_check', 'KR') 这是我在节点端所做的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-04
  • 2019-10-30
  • 2021-12-27
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多