服務端 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>