You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Socket.io运行报错ReferenceError: client is not defined如何解决

错误原因

client是io.on('connection')连接回调的入参,作用域仅存在于该回调函数内部,你将client.on的事件监听逻辑写在了回调外部,无法访问到client变量,因此触发引用报错。
同时你当前写在外部的io.sockets.emit('setRelay', bodyRelay)会在服务启动时立即执行,此时还没有客户端完成连接,消息不会被任何客户端收到,也建议调整到合适的逻辑位置。

修正后的完整代码

var express = require ('express');
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = 3000;

let bodyRelay = {
    relayId: 'RELAY-123',
    state: 1
}

app.use(express.static(__dirname + '/node_modules'));
app.get('/', function(req, res, next) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(client) {
    console.log('a user has connected');
    // 客户端连接成功后再发送初始状态
    client.emit('setRelay', bodyRelay);
    // 所有client相关的监听逻辑都要放到连接回调内部
    client.on('getRelay', function (state) {
        bodyRelay = state;
        console.log('id: ' + client.id + 'bodyRelay: ' + JSON.stringify(bodyRelay));
        // io.sockets.emit('setRelay', bodyRelay);
    });

    client.on('disconnect', function() {
        console.log('a user has disconnected');
    });
});

server.listen(port, () => {
    console.log('Server is running on port: ' + port)
});

补充说明

如果需要给所有已连接的客户端广播消息,保留io.sockets.emit写法即可,如果只需要给当前触发事件的客户端回消息,用client.emit即可。

内容的提问来源于stack exchange,提问作者jhn lovatic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 05:24:04