我刚刚安装了这些 nodejs 和 socket.io,但是在让客户端连接到服务器时遇到了问题。
在我的服务器中,我有:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, 'localhost');
console.log('Server running at http://localhost:3000/');
var io = require('socket.io').listen(3000);
io.sockets.on('connection', function (socket) {
socket.emit('Hi.') ;
});
在我的客户上:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('connect', function () {
socket.emit('set nickname', confirm('What is your nickname?'));
socket.on('ready', function () {
console.log('Connected !');
socket.emit('msg', confirm('What is your message?'));
});
});
我在 Chrome 检查器中遇到了一些错误:
GET http://localhost:9261/socket.io/socket.io.js 404 (Not Found)
Uncaught ReferenceError: io is not defined