简体   繁体   English

服务器未收到从客户端发送的 socket.io 消息

[英]socket.io messages sent from client aren't received in server

I am trying to play around with socket.io and figure out if it suits us.我正在尝试使用 socket.io 并弄清楚它是否适合我们。 I have ran into a problem while trying stuff out.我在尝试东西时遇到了问题。

so in my server i have the following code:所以在我的服务器中,我有以下代码:


const express = require('express')
const bodyParser = require('body-parser')
const helmet = require('helmet')


const apiLogger = require('morgan')


const apiLoggerFormat = 'dev'

const app = express()
const redisAdapter = require('socket.io-redis');
const server = require('http').createServer(app)
const io = require('socket.io')(server)
io.adapter(redisAdapter({ host: process.env.REDIS_HOSTNAME, port: process.env.REDIS_HOSTNAME }))


io.on('connection', () =>{
    console.log('a user is connected')
    io.emit('hi')

    io.on("initial_data", () => {
        console.log("THIS IS SPARTA")
    })

})

app.use(apiLogger(apiLoggerFormat))

app.set('port', constants.port)
app.set('trust proxy', 1)
app.use(bodyParser.json({ limit: '1mb', extended: true }))
app.use(bodyParser.urlencoded({ extended: true }))



        server.listen(app.get('port'), () => {
logger.info(`Server listening on port ${app.get('port')}`)}
        


module.exports = server

and on the client i have the following component在客户端我有以下组件


import React, {Component} from 'react'
import socketIOClient from "socket.io-client";

let socket;

class PersonalFoodComponent extends Component {
    constructor() {
        super();
        this.state = {
            food_data: []
        }
        socket = socketIOClient(process.env.SERVER_URL);

    }


    changeData = () => socket.emit("initial_data");

    getData = (food_data) => {
        console.log(food_data);
        this.setState({food_data: Object.values(food_data)});
    };

    componentDidMount() {
        var state_current = this;
        socket.emit("initial_data");
        socket.on("get_data", this.getData);
        socket.on("change_data", this.changeData);
    }

    //
    componentWillUnmount() {
        socket.off("get_data");
        socket.off("change_data");
    }

    getFoodData() {
        return this.state.food_data.map(food => {
            return (
                    <ul style={{color: "red"}}>
                        <li> {food.buyer} </li>
                        <li> {food.key} </li>
                    </ul>
            )
        })
    }

    sendTestEvent() {
        console.log("here", socket.emit("initial_data"))
        socket.emit("initial_data")
    }

    render() {

        return (
                <div>
                    <button onClick={()=>this.sendTestEvent()}>click me!</button>
                    {this.getFoodData()}
                </div>
        )
    }
}

export default PersonalFoodComponent;

As soon as I switch to the component I see that it is able to connect, which is a good thing.一旦我切换到组件,我就会看到它能够连接,这是一件好事。 I am also able to send data from the server to the client.我还可以将数据从服务器发送到客户端。

but, the events that i am trying to send from the client to the server aren't being processed.但是,我试图从客户端发送到服务器的事件没有被处理。 the initial_data is just not getting received by the server. initial_data只是没有被服务器接收。 does anyone have any idea why this might happen ?有谁知道为什么会发生这种情况?

change改变

io.on('connection', () =>{
    console.log('a user is connected')
    io.emit('hi')

    io.on("initial_data", () => {
        console.log("THIS IS SPARTA")
    })

})

to

io.on('connection', socket =>{
    console.log('a user is connected')
    io.emit('hi')

    socket.on("initial_data", () => {
        console.log("THIS IS SPARTA")
    })

})

then it should work ;)那么它应该工作;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM