首先是一点点代码。这是服务器代码:
var http = require('http');
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
switch(path){
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<!DOCTYPE html><html><head><title>Learn socket.io</title><meta charset="UTF-8"></head><body><h1>OK</h1></body></html>');
break;
case '/socket.html':
fs.readFile(__dirname + path, 'UTF-8', function(error, data){
if(error){
res.writeHead(404);
res.end('<!DOCTYPE html><html><head><title>Learn socket.io</title><meta charset="UTF-8"></head><body><h1>OEPS!!! 404 error</h1></body></html>');
}else{
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
res.end(data, 'UTF-8');
}
});
break;
default:
res.writeHead(404);
res.end('<!DOCTYPE html><html><head><title>Learn socket.io</title><meta charset="UTF-8"></head><body><h1>OEPS!!! 404 error</h1></body></html>');
}
});
server.listen(8001);
io.listen(server);
//io.set('log level', 1);
//io.sockets.on('connection', function(socket){
//socket.emit('message', {'content':'Server sending connection event'});
//});
console.log('Serveur started on 8001');
以及socket.html页面:
<html>
<head>
<title>File uploader</title>
<script src="http://localhost:8001/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('connecting', function(){
console.log('Socket fire connecting event.');
});
socket.on('connect', function(){
console.log('Socket fire connect event.');
});
socket.on('disconnect', function(){
console.log('Socket fire disconnect event.');
});
socket.on('message', function(data){ //message, callback
console.log(data.content);
});
socket.on('connect_failed', function(){
console.log('socket could not connect.');
});
socket.on('error', function(){
console.log('An error occured.');
});
</script>
</head>
<body>
<h1>This is our new socket.html file</h1>
</body>
</html>
这里没有什么特别的,只有代码来学习这些东西。一切都很好,但是当我取消注释&#34; io.set(&#39; log level&#39;,1);&#34;或者io.socket.on ...,我再也无法连接到服务器了。此外,在命令提示符(Windows ...)我得到了&#39;信息 - &#39;或者&#39;调试 - &#39;,但仅此而不是我在不同的博客中看到的,我应该有这样的东西:info - socket.io started,debug - serve static content /socket.io.js < / p>
有人可以说我的代码中有什么问题吗?
提前谢谢你, 米歇尔
答案 0 :(得分:1)
server.listen(8001);
之后
将io.listen(server);
更改为io = io.listen(server);
以访问您的socket.io服务器实例。