【问题标题】:Node SocketIo - Client not emitting?节点 SocketIo - 客户端不发射?
【发布时间】:2021-06-08 02:46:45
【问题描述】:

我遇到了 Node SocketIo 客户端不发送数据的问题。因此,当客户端在 index.html 中连接时确实记录了“已连接这是一个测试”,但是它没有 socket.emit('cool'),没有错误,也似乎没有登录 server.js。我不确定为什么它没有发出或服务器没有监听。

服务器.js

const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketio(server);

const PORT = 3002;

app.use(express.static(path.join(__dirname, 'public')));


// run when client connects
io.on('connection', () => {
    console.log('New WS connection...');
    io.emit('connection', 'This Is A Test');
});

io.on('cool', (msg) => {
    console.log(msg);
});


server.listen(PORT, () => console.log(`server running on port ${PORT}`));

index.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://' + document.domain + ':' + location.port);
  socket.on('connection', function(data){
    console.log("connected", data);
    socket.emit('cool', 'MSG');
  });
</script>
</body>
</html>

【问题讨论】:

    标签: node.js socket.io


    【解决方案1】:

    在您的服务器上,您需要在特定连接的套接字上侦听 cool 消息,而不是在 io 对象上。 io 对象除了宣布新连接的套接字之外没有特定的套接字消息。要侦听来自特定套接字的消息,您需要连接的套接字本身的侦听器。添加该侦听器的通常位置是在connection 事件中,您会看到新连接的套接字对象。

    所以改变这个:

    // run when client connects
    io.on('connection', () => {
        console.log('New WS connection...');
        io.emit('connection', 'This Is A Test');
    });
    
    io.on('cool', (msg) => {
        console.log(msg);
    });
    

    到这里:

    // run when client connects
    io.on('connection', (socket) => {
        console.log('New WS connection...');
    
        // send a test event back to the socket that just connected
        socket.emit('test', 'This Is A Test');
    
        // listen for the cool message on this new socket
        socket.on('cool', (msg) => {
            console.log(msg);
        });
    });
    

    另外,你真的不应该发出系统使用的事件名称,例如connection。这就是为什么我将事件名称更改为test,这样它就不会与 socket.io 本身使用的名称冲突。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2018-03-23
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多