0
我的問題在於,當有人連接到頁面時,它應該使用node.js在命令行上打印'a user connected'
但是該消息從不顯示,因此它不會在用戶註冊時訪問該頁面(全部在本地主機完成)。我會在下面發佈一些代碼,也許你可以找到問題並幫助我?當用戶連接時,socket.io沒有註冊
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');
});
仍然沒有成功,但在/socket.io目錄下沒有socket.io.js文件,但只有一個index.js文件。爲什麼我的原始資源如此之久是因爲我只能在/socket.io/node_modules/socket.io-client/目錄下找到socket.io.js。 – IE8IsBetterThenGoogleChrome 2014-09-28 00:07:06
這個文件在這個文件夾上並不存在,socket.io默認在這個位置提供它自己。如果你的路徑有效,你是否嘗試過'var socket = io.connect()'而不是'IO()'? (檢查你的控制檯是否有錯誤,例如'IO未定義') – topheman 2014-09-28 00:20:08
啊我知道了,在我的JS文件中變量被稱爲'io'(小寫),但是我在'index.html'中使用大寫字母來調用它,文件。改變它並添加'.connect()'似乎解決了我的問題! – IE8IsBetterThenGoogleChrome 2014-09-28 00:33:28