我是Node.js和Socket.IO的新手,我想尝试在上解释的示例

https://socket.io/get-started/chat/

我做了所有我必须做的事情,并且它起作用了:我打开了两个选项卡,消息同时出现在两个客户端中,但是由于某种原因,它们在5/6秒后出现(有时甚至更晚)。
你们知道为什么吗(我正在使用Windows 10)?

这是index.js文件代码:

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log(msg)
  socket.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});


这是html代码:

<!doctype html>
<html>

<head>
    <title>Socket.IO chat</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font: 13px Helvetica, Arial;
        }

        form {
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 0;
            width: 100%;
        }

        form input {
            border: 0;
            padding: 10px;
            width: 90%;
            margin-right: .5%;
        }

        form button {
            width: 9%;
            background: rgb(130, 224, 255);
            border: none;
            padding: 10px;
        }

        #messages {
            list-style-type: none;
            margin: 0;
            padding: 0;
        }

        #messages li {
            padding: 5px 10px;
        }

        #messages li:nth-child(odd) {
            background: #eee;
        }

        #messages {
            margin-bottom: 40px
        }
    </style>
</head>

<body>
    <ul id="messages"></ul>
    <form action="">
        <input id="m" autocomplete="off" />
        <button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>

    <script>
        var socket = io();

        $(function () {
            $('form').submit(function () {
                socket.emit('chat message', $('#m').val());
                $('#m').val('');
                return false;
            });
            socket.on('chat message', function (msg) {
                $('#messages').append($('<li>').text(msg));
                window.scrollTo(0, document.body.scrollHeight);
            });
        });
    </script>
</body>

</html>


这是package.json:

{
    "name": "socket-example",
    "version": "0.0.1",
    "description": "my first socket.io app",
    "dependencies": {
        "engine.io": "^3.1.5",
        "express": "^4.15.2",
        "socket.io": "^2.0.4"
    }
}

最佳答案

似乎是一个已知问题->

https://github.com/socketio/socket.io/issues/3179

因此,在您的index.js文件中。

变化->

var io = require('socket.io')(http);


至->

var io = require('socket.io')(http, { wsEngine: 'ws' });


这样做,我现在获得即时反馈,运行Windows 10.。

10-05 20:41
查看更多