Node.js应用程序从浏览器接收发射,但浏览器不接收回发

时间:2017-09-24 21:36:52

标签: javascript node.js socket.io

我似乎无法弄清楚为什么node.js服务器连接正常,并从浏览器中接收到emit(),但是当我尝试从node.js发回()时它没有到达浏览器。我在这里错过了什么吗?

控制台日志显示“已接收测试”,但未显示“测试已发送到浏览器”。

(index.php)摘录:

<script language="javascript" type="text/javascript">       
        var socket = io.connect('https://www.example.com:2053', {secure: true});
        socket.on('connect', function() {
            socket.emit('join', '19AFA53df7715sfs484');
        });


        socket.on('testsend', function () {
            console.log('Test Sent To Browser');
        });

        $(document).ready(function () {
            $(this).on('click', '.mainlogo', function (e) {
                e.preventDefault();
                socket.emit('testrecieve');
            });
        });

</script>

套接字代码(pipe.js):

var fs = require('fs');

var options = {
    ca: fs.readFileSync(__dirname + '/ca.pem'),
  key: fs.readFileSync(__dirname + '/file.pem'),
  cert: fs.readFileSync(__dirname + '/file.crt')
};

var express = require('express'),
app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

var https = require('https'),
server = https.createServer(options, app),
io = require('socket.io')(server, { origins: '*:*'});

server.listen(2053);

// routing
app.get('/', function (req, res) {
  res.sendfile('/index.php');
});

io.sockets.on('connection', function (socket) {

    socket.on('join', function(uauth){
        socket.join('messages');
        socket.join(''+uauth+'');
    });

    socket.on('testrecieve', function () {
        socket.broadcast.emit('testsend');
        console.log('Test Recieved');
    });

});

2 个答案:

答案 0 :(得分:1)

有一个错误,它是socket.emit,而不是socket.broadcast.emit

socket.on('testrecieve', function () {
    socket.emit('testsend');
    console.log('Test Recieved');
});

socket.broadcast.emit将发送给除新连接之外的所有人。

答案 1 :(得分:1)

问题是socket.broadcast.emit会将消息发送给除新创建的连接之外的所有其他客户端。这不是你想要的。您应该使用socket.emit代替。