如果没有指定房间,客户端会收到消息,但在指定房间时,我无法在客户端收到消息。
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
在server.js上的我在下面尝试了几个选项,但仍然无法发出“收到消息”#39;在客户端:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
使用带角度为4的最新socket.io库
答案 0 :(得分:1)
基于我在您的客户端和服务器端代码上看到的内容,我认为问题出在clientSide代码中......
在你的服务器上,在'subscribe'事件中,服务器也在监听'send-message'事件,你永远不会从客户端发出!!
因此,如果您发出带有数据的“发送消息”事件(这应包括消息)作为参数,则服务器才会向客户端发出“消息接收”事件。
希望这有帮助!