Socket.io连接但不在客户端上接收消息

时间:2017-11-23 13:47:32

标签: node.js socket.io eventemitter

我使用socket.io实现了服务器和客户端,并且服务器工作正常,当某个客户端连接它时我会登录,但是当我发出一个事件时它没有到达客户端,它遵循代码来分析:

来自socket对象的console.log就是这样说的:

连接:假, 断开:真

服务器:



'use strict';

const chalk = require('chalk');
const _ = require('lodash');
const fs = require('fs');

let options = {
    key: fs.readFileSync("privkey.pem"),
    cert: fs.readFileSync("cert.pem")
  };
const app = require('express')(options);
const https = require('https').Server(app);
const io = require('socket.io')(https,{origins:'*:*'});
const bodyParser = require('body-parser');
const multer = require('multer'); // v1.0.5
const upload = multer(); // for parsing multipart/form-data

const sockets = {};

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

https.listen(3002, function () {
    console.log(chalk.yellow("Serviço rodando na porta 3002"));
});
io.on('connection', function (socket) {
    console.log(chalk.green("Cliente Conectado"));
    sockets[socket.id] = socket;

    socket.on('disconnect', function () {
        console.log(chalk.red("Cliente Disconectado"));
        delete  sockets[socket.id];
    });
});

app.post('/atualizador', upload.array(), function (req, res) {
    _.each(sockets,function(socket,idSocket){
        console.log(idSocket);
        socket.emit('posicao',req.body);
    });
    res.send('Atualizador ON');
});




客户端:



<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
  localStorage.debug = '*';
  const socket = io.connect('https://localhost:3002/atualizador',{'forceNew': true});

  console.log(socket);

  socket.on('connection', function (socket) {
    console.log(socket);
    socket.on('posicao', function (msg) {
      console.log("Ok");
      console.log(msg);
    });
    socket.on('teste', function (msg) {
      console.log("Ok");
      console.log(msg);
    });
  });

</script>
&#13;
&#13;
&#13;

0 个答案:

没有答案