【问题标题】:ReactJS with Socket.IO, server emits to client, but client doesn't emit to server带有 Socket.IO 的 ReactJS,服务器向客户端发出,但客户端不向服务器发出
【发布时间】:2019-07-04 04:43:37
【问题描述】:

我正在学习 Socket.IO,我正在尝试做一些非常简单的事情,在连接时从服务器向客户端发出一些文本(这可行),并从客户端向服务器发出信号(这不起作用)。 这是我的客户端代码(ReactJS 组件)

import React, { Component } from 'react';

const io = require('socket.io-client');
const socket = io.connect('http://x.x.x.x:xxxx');

class Client extends Component {
    constructor(props) {
        super(props);
        this.state = {
            String1: 'No text yet',
        }
    }
    componentDidMount() {
        socket.on("message", data => this.setState({ String1: data }));

        { socket.emit('Update', 'test') }
    };
    render() {
        return (
            <div>
                String1 is: {this.state.String1}
            </div>
        );
    }
}
export default Client;

这是我的服务器代码(NodeJS):

const server = require('http').createServer() 
const io = require('socket.io')(server) 

io.on('connection', function (socket) { 
        console.log('client connected'); 
        socket.emit('message', 'You are connected'); 
        io.on('Update', function(ttext){     
                console.log('Updated'); 
        }); 
}); 

io.sockets.on("disconnect", () => console.log("Client disconnected")); 

server.listen(3000, function (err) { 
          if (err) throw err 
          console.log('listening on port 3000') 
})

客户端:在浏览器上,我正确地看到“还没有文本”,一旦客户端连接到服务器,它就会变为“您已连接”。

但是,在服务器端,每次客户端浏览器刷新时,我只能在终端上看到“客户端已连接”,但没有其他内容,没有“已更新”,也没有“客户端已断开连接”。

我做错了什么?

【问题讨论】:

    标签: reactjs socket.io


    【解决方案1】:

    我认为您需要将消息事件处理程序附加到提供的 socket 连接对象,而不是 io 服务器实例:

    socket.on('Update', function(ttext){     
        console.log('Updated'); 
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 2013-09-09
      • 2019-04-23
      • 1970-01-01
      相关资源
      最近更新 更多