簡體   English   中英

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

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

io.on(“連接”)不起作用。 我一直在尋找我的問題的答案很長時間,但我沒有找到它。 我正在使用 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>

我的目錄樹如下所示:
套接字聊天/
index.js(服務器文件)
封裝.json
封裝鎖.json
節點模塊/
上市/
索引.html

我記得在更改和文本“站點正在運行”之后重新啟動 index.js。 在我看來? 問題是什么。 提前感謝那些將解決我的問題的人:對不起,如果我有一個愚蠢的錯誤:|

有必要添加到 html 頁面:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM