写了一个简单的demo,直接上代码吧。用的时候注意一下版本号,可能 socket.io 的 API 有修改~
效果图
index.html
websocket测试
socket_server.js
var app = require('http').createServer(handler)var io = require('socket.io')(app);var fs = require('fs');app.listen(8080);function handler(req, res) { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('Hello Socket Lover!
');}io.on('connection', function (socket) { socket.emit('news', { data : 'server world' }); socket.on('test_event', function (data) { console.log('receive data from client. data : ' + JSON.stringify(data)); var str = data.data + "(from server by " + new Date().getTime() + ")"; socket.emit('news', { data : str}); }); socket.on('disconnect', function () { console.log('websocket close. -- server log'); }); // var num = 1; // setInterval(function xx(params) { // socket.emit('news', { num: num++}); // }, 1 * 1000);});