如何查看socket.html的输出? [英] How to see the output of socket.html?
问题描述
我是 node.js 的新手.我正在尝试实施 danielnill 示例 教程
i am newbie to node.js. I was trying to implement danielnill example tutorial
server.js
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case 'socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8001);
io.listen(server);
socket.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect();
</script>
<div>This is our socket.html file</div>
</body>
</html>
当我尝试从浏览器运行这个 http://localhost:8001/socket.html
url 时.它转到默认情况,而不是转到socket.html"情况.
when ever i am trying run this http://localhost:8001/socket.html
url from browser. Its goes to default case instead going to 'socket.html' case.
请帮我在这个例子中执行 'socket.html' 案例.
Pls help me to execute 'socket.html' case in this example.
推荐答案
您发布的内容有两个问题:
There are two issues with what you have posted:
path
变量等于/socket.html
当 URLhttp://localhost:8001/socket.html
为请求,而不是socket.html
;您需要相应地更新 case 语句.
The
path
variable equals/socket.html
when the URLhttp://localhost:8001/socket.html
is requested, notsocket.html
; you need to update the case statement accordingly.
fs.readFile
回调将无法将响应写回客户端(浏览器),因为 response.end();
将已经被调用;您需要将 response.end()
移动到每个 case
语句中.
The fs.readFile
callback will not be able to write the response to back to the client (browser), as response.end();
will have already been called; you need to move response.end()
into each of the case
statements.
这是更新的代码:
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
response.end();
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
response.end();
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
server.listen(8001);
io.listen(server);
这篇关于如何查看socket.html的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!