【问题标题】:NodeJS/Socket.io not receiving event from clientNodeJS/Socket.io 没有收到来自客户端的事件
【发布时间】:2016-06-22 05:06:00
【问题描述】:

在尝试设置一个简单的 NodeJS 服务器和 Socket.io 客户端以使用 WebSockets 测试某些东西时,我偶然发现了一些愚蠢的东西。我很确定这是一件愚蠢的事情我已经做过,因为我之前使用过 NodeJS/Socket.io 并且从未遇到过这个问题。

使用下面的代码,我可以在客户端接收到来自服务器的 'tick' 事件,但服务器似乎无法接收来自客户端的 'ping' 事件。 'tick' 用于确保 server->client 正常工作,'ping' 用于测试 client->server。

使用最新的 Socket.io (1.4.6) 和 express (4.14.0)

server.js:

var express = require('express');
var app = require('express')();
var server = require('http').createServer(app);
var sio = require('socket.io')(server);
var path = require('path');

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

// Socket.io
sio.on('connection', (socket) => {
    // Store socket ID
    var socketID = socket.conn.id;

    // Log connection
    console.log('Connection:', socketID);

    // Ping event
    socket.on('ping', (message) => {
        console.log('Ping:', socketID, '-', (message || '(no message>'));
    });

    // Tick event
    var tick = function(){
        var now = new Date().getTime().toString();
        socket.emit('tick', now);
    }
    setInterval(tick, 5000);

    // Disconnect event
    socket.on('disconnect', () => {
        console.log('Disconnected:', socketID);
    });
});

server.listen(4100, () => {
    console.log('Listening on :4100');
});

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Websockets Benchmark</title>
</head>
<body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        // Socket.io
        var sio = io();

        // Connection event
        sio.on('connect', () => {
            console.log('Connected');

            sio.emit('ping', 'on connect');
        });

        // Tick event
        sio.on('tick', (time) => {
            console.log('Tick', time);
        });

        // Error event
        sio.on('error', (e) => {
            console.error(e);
        });
    </script>
</body>

【问题讨论】:

    标签: javascript node.js websocket socket.io


    【解决方案1】:

    希望我理解你的问题... 我使用socket.io 进行了一些聊天工作,所以也许它会对您有所帮助。 在这里:

     <div class="searchBox" style="height: 600px ; width: 500px">
          <div style=";width:400px;border-right:1px solid black;;overflow:scroll-y;">
             <b style="color: black ;text-decoration: underline">USERS:</b>
             <div id="users" style="color: black"></div>
          </div>
          <div style=";width:300px;height:250px;overflow:scroll-y;padding:10px;">
             <b style="color: black ; text-decoration: underline">CONVERSATION:</b>
             <div id="conversation" style="color: black"></div>
             <input id="data" style="width:200px;" />
             <button id="datasend" style="color: #0f0f0f;">send</button>
          </div>
    

    和js:

    var socket = io.connect('http://localhost:8080');
        // on connection to server, ask for user's name with an anonymous callback
        socket.on('connect', function(){
            // call the server-side function 'adduser' and send one parameter (value of prompt)
            socket.emit('adduser', prompt("What's your name?"));
        });
        // listener, whenever the server emits 'updatechat', this updates the chat body
        socket.on('updatechat', function (username, data) {
            $('#conversation').append('<b>'+username + ':</b> ' + data + '<br>');
        });
        // listener, whenever the server emits 'updateusers', this updates the username list
        socket.on('updateusers', function(data) {
            $('#users').empty();
            $.each(data, function(key, value) {
                $('#users').append('<div>' + key + '</div>');
            });
        });
        // on load of page
        $(function(){
            // when the client clicks SEND
            $('#datasend').click( function() {
                var message = $('#data').val();
                $('#data').val('');
                // tell server to execute 'sendchat' and send along one parameter
                socket.emit('sendchat', message);
            });
            // when the client hits ENTER on their keyboard
            $('#data').keypress(function(e) {
                if(e.which == 13) {
                    $(this).blur();
                    $('#datasend').focus().click();
                }
            });
        });
    

    服务器:

    var app = require('./app');
    var http = require('http');
    var server = http.createServer(app);
    var io = require('socket.io').listen(server);
    
    server.listen(8080, function() {
        console.log("Gym Project is listening to: http://127.0.0.1:8080");
    });
    
    // routing
    app.get('/', function (req, res) {
        res.sendfile(__dirname + '/index.html');
    });
    
    
    // usernames which are currently connected to the chat
    var usernames = {};
    
    io.sockets.on('connection', function (socket) {
    
        // when the client emits 'sendchat', this listens and executes
        socket.on('sendchat', function (data) {
            // we tell the client to execute 'updatechat' with 2 parameters
            io.sockets.emit('updatechat', socket.username, data);
        });
    
        // when the client emits 'adduser', this listens and executes
        socket.on('adduser', function(username){
            // we store the username in the socket session for this client
            socket.username = username;
            // add the client's username to the global list
            usernames[username] = username;
            // echo to client they've connected
            socket.emit('updatechat', 'SERVER', 'you have connected');
            // echo globally (all clients) that a person has connected
            socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
            // update the list of users in chat, client-side
            io.sockets.emit('updateusers', usernames);
        });
    
        // when the user disconnects.. perform this
        socket.on('disconnect', function(){
            // remove the username from global usernames list
            delete usernames[socket.username];
            // update list of users in chat, client-side
            io.sockets.emit('updateusers', usernames);
            // echo globally that this client has left
            socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
        });
    });
    

    这是与一些客户的非常简单的聊天... 可能有帮助:)

    【讨论】:

    • 谢谢 - 你的代码没有直接让我找到答案,但我认为我的事件名称与 Socket.io 的名称冲突
    【解决方案2】:

    无法判断ping 事件是否被 Socket.io 占用,或者以下行导致了问题:

    console.log('Ping:', socketID, '-', (message || '(no message)'));
    

    无论哪种方式,通过将事件名称更改为ev:ping(无论如何都更容易理解),并简化该行,它已修复! :)

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 2019-02-01
      • 2018-11-02
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2018-08-12
      • 2015-10-12
      • 1970-01-01
      相关资源
      最近更新 更多