我的问题是,当有人连接到该页面时,应该使用 node.js 在命令行上打印 'a user linked'
但该消息从未显示,因此它没有注册当用户访问该页面时(所有操作都在本地主机中完成)。我将在下面发布一些代码,也许您可以找到问题并帮助我?
JSON:
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"express": "^4.9.5",
"socket.io": "^1.1.0"
}
}
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; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/Users/kavehkhorram/Desktop/chat-example/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
<script>var socket = IO();</script>
</body>
</html>
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){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
最佳答案
替换
<script src="/Users/kavehkhorram/Desktop/chat-example/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>
由
<script src="/socket.io/socket.io.js"></script>
这是 Node 模块(通过 http)公开 socket.io 客户端 api 的正确(默认)url。
关于javascript - 用户连接时 socket.io 未注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26080225/