标签:
websocket原本是html5下实现长链接的一个特性,当前已被众多浏览器支持。
在websocket协议中,首先通过http交换一次握手,明确将协议升级至websocket。同时建立一个TCP通道,以frame帧的方式交换数据。
在node环境下基本功能实现如下:
首先npm install socket.io
1、app.js,初始化socket.io
var srv = http.createServer(app).listen(app.get(‘port‘), function(){ console.log(‘Express server listening on port ‘ + app.get(‘port‘)); }); var io = require(‘socket.io‘).listen(srv); server.initServer(io);
2、server.js实现服务器端代码
exports.initServer = function(io){ io.on(‘connection‘,function(socket){ console.log(‘connection‘); socket.on(‘disconnect‘,function(msg){ console.log(‘disconnect‘); }); socket.on(‘msg1‘,function(msg){ console.log(msg); socket.emit(‘back‘,{key:‘fredric&sinny‘}); }); }); }
3、客户端代码
<!DOCTYPE html> <html> <head> <script src = "socket.io.js"></script> <script> var socket = io.connect(‘http://localhost:3000‘); function sendmsg(){ console.log(‘start sendmsg‘); socket.emit(‘msg1‘,{key:‘fredric‘}); } socket.on(‘back‘,function(msg){ alert(msg.key); }); </script> </head> <body> <button type="button" onclick=‘sendmsg()‘>Click Me!</button> </body> </html>
浏览器端调试网络接口如下:
标签:
原文地址:http://www.cnblogs.com/Fredric-2013/p/4293700.html