Socket.io事件监听器无法在客户端运行

时间:2018-11-01 09:49:25

标签: sockets socket.io

这是我的index.html

<!doctype html>
<html>
<head>
    <title>Socket.IO chat</title>
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
    <ul id="messages"></ul>
    <script>
    var socket = io();
    socket.on('testerEvent', function(data){
        console.log(data)
    });
    </script>
</body>
</html>

这是我的index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

io.on('connection', function(socket){
    socket.emit('testerEvent', { description: 'A custom event named testerEvent!'});
});

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

在index.html中,侦听器不适用于客户端,而适用于服务器端。 我不知道怎么了。

1 个答案:

答案 0 :(得分:1)

它没有监听任何事件,因为您没有从听的地方告诉它。 试试这个:

var connectionOptions = {

"force new connection": true,
"reconnectionAttempts": "infinity",
"timeout": 10000,
"transports": ["websocket"]
};
const socket = io(/*your server*/, connectionOptions);
相关问题