我正在尝试使用教程,其中可以使用Node.js和Socket.io与各种用户协作使用画布。以下是用于创建服务器的源文件。但是,当我打开浏览器时,它仍然在等待localhost。可能是什么原因?
我尝试更改端口号,以防万一造成问题。
// Including libraries
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
static = require('node-static'); // for serving files
// This will make all the files in the current folder
// accessible from the web
var fileServer = new static.Server('./');
// This is the port for our web server.
// you will need to go to http://localhost:8080 to see it
app.listen(4994);
// If the URL of the socket server is opened in a browser
function handler (request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
});
}
// Delete this row if you want to see debug messages
//io.set('log level', 1);
// Listen for incoming connections from clients
io.sockets.on('connection', function (socket) {
// Start listening for mouse move events
socket.on('mousemove', function (data) {
// This line sends the event (broadcasts it)
// to everyone except the originating client.
socket.broadcast.emit('moving', data);
});
});
答案 0 :(得分:0)
解释我的更改
“定义JavaScript代码应该以”严格模式“执行。” - http://www.w3schools.com/js/js_strict.asp
将变量名称static更改为_static,因为static是严格模式下的保留关键字。
这是主要问题,你必须添加request.on('data')事件,否则你必须在request.addListener之后恢复('end'...作为@greed说。
我在代码中更改了此行的位置,因为您必须在使用“listen(server)”之前设置服务器。
"use strict"; //good practice
var http = require('http'),
_static = require('node-static'); // for serving files
// This will make all the files in the current folder
// accessible from the web
var fileServer = new _static.Server('./');
// This is the port for our web server.
// you will need to go to http://localhost:8080 to see it
// If the URL of the socket server is opened in a browser
var server = http.createServer(function(request, response) {
request.on('data', function (chunk) {}); //you have to add on ('data')
request.addListener('end', function () {
fileServer.serve(request, response);
});
});
console.log("Starting up the server port 4994");
server.listen(4994);
var io = require('socket.io').listen(server); //you have to setup server first so this is the correct place to io.listen
// Delete this row if you want to see debug messages
//io.set('log level', 1);
// Listen for incoming connections from clients
io.sockets.on('connection', function (socket) {
// Start listening for mouse move events
socket.on('mousemove', function (data) {
// This line sends the event (broadcasts it)
// to everyone except the originating client.
socket.broadcast.emit('moving', data);
});
});
答案 1 :(得分:0)
您需要在提供文件后恢复请求。
// If the URL of the socket server is opened in a browser
function handler (request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
}).resume();
}