修改上一篇文章的node.js代码,支持默认页及支持中文
服务端 app.js
var app = require('http').createServer(handler) var io = require('socket.io')(app); var fs = require('fs'); var url = require("url"); app.listen(80); function handler (req, res) { var pathname = url.parse(req.url).pathname; if(pathname == "/") { pathname = "/index.html"; } fs.readFile(__dirname + pathname, 'utf-8', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + pathname); } res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'}); res.end(data); }); } io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); socket.on('disconnect', function (data) { console.log('disconnect:' + data); }); });
说明:
1、如果没有指定默认页,默认加载/index.html页面
2、主要是通过这句话来支持中文 res.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
客户端 index.html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>demo</title> </head> <body> <script src="/socket.io/socket.io.js"></script> <script src="jquery-2.1.1.js"></script> <script> var socket = io('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); $(document).ready(function(){ alert("页面加载完成!"); }); </script> </body> </html>