2017-07-28 227 views
1

當沒有指定房間時客戶端收到消息,但指定房間時我無法在客戶端上接收消息。socket.io客戶端沒有收到消息

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上server.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); 
}); 

我曾嘗試下面幾個選項,但仍無法發出 '消息收到' 在客戶端:

// 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); 

使用帶角度的最新socket.io庫4

回答

1

基於我對你的客戶方和服務器端代碼中看到的,我相信這個問題是在客戶方代碼...

在你的服務器上,「訂閱」事件中的服務器也被監聽「發送 - 消息'事件,你永遠不會從客戶端發出!

因此,如果您發出「發送消息」事件與數據(這應包括郵件)作爲參數,只有這樣,服務器會發出「消息收到」事件給客戶..

希望這有助於!

相關問題