服务端 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
demo