简体   繁体   English

Node.js Socket.io:io.on(“连接”)不工作

[英]Node.js Socket.io: io.on ('connection') is not working

io.on ('connection') doesn't work. io.on(“连接”)不起作用。 I have been looking for an answer to my question for a long time, but I have not found it.我一直在寻找我的问题的答案很长时间,但我没有找到它。 I am using Express + Socket.io bundle, so I expected there might be problems.我正在使用 Express + Socket.io 捆绑包,所以我预计可能会有问题。 I found in one answer to a question to use express.static, but it didn't help.我在一个问题的答案中找到了使用 express.static,但它没有帮助。 Vod file in which the server code:服务器代码所在的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}`); });

Here is the index.html file:这是 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>

My directory tree looks like this:我的目录树如下所示:
SocketChat/套接字聊天/
index.js (server file) index.js(服务器文件)
package.json封装.json
package-lock.json封装锁.json
node_modules/节点模块/
public/上市/
index.html索引.html

I remember to restart index.js after changes and the text "Site is working."我记得在更改和文本“站点正在运行”之后重新启动 index.js。 it seems to me?在我看来? What is the problem.问题是什么。 Thanks in advance to those who will solve my question: Sorry if I have a silly mistake :|提前感谢那些将解决我的问题的人:对不起,如果我有一个愚蠢的错误:|

It was necessary to add to the html page:有必要添加到 html 页面:

 <script> var socket = io (); </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM