【发布时间】:2021-07-28 09:19:10
【问题描述】:
io.on ('connection') 不起作用。我一直在寻找我的问题的答案很长时间,但我没有找到它。我正在使用 Express + Socket.io 捆绑包,所以我预计可能会有问题。我在一个问题的答案中找到了使用 express.static,但它没有帮助。服务器代码所在的vod文件:
var express = require('express')
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var PORT = 3000;
var connections = [];
app.use(express.static(__dirname + '/public/'));
app.get('/', function (request, responce) {
responce.sendFile(__dirname + '/public/index.html');
});
io.sockets.on('connection', function (socket) {
connections.push(socket);
console.log(connections);
console.log('New user connected to chat!');
socket.on('disconnect', function (data) {
connections.splice(connections.indexOf(socket), 1);
console.log('User disconnected.');
});
});
server.listen(PORT, function () {
console.log(`Start listening on http://localhost:${PORT}`);
});
这里是 index.html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io chat</title>
</head>
<body>
Site is working!
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
</script>
</html>
我的目录树如下所示:
SocketChat/
index.js(服务器文件)
package.json
package-lock.json
node_modules/
public/ index.html
我记得在更改和文本“站点正在运行!”后重新启动 index.js在我看来。问题是什么?提前感谢那些将解决我的问题的人。对不起,如果我有一个愚蠢的错误:|
【问题讨论】:
标签: html node.js express http socket.io