HTML5之WebSocket入门3

socket.io为什么会诞生呢?请看下面文字说明。

为什么需要socket.io?

node.js提供了高效的服务端运行环境,但是由于浏览器端对HTML5的支持不一,为了兼容所有浏览器,提供卓越的实时的用户体验,并且为程序员提供客户端与服务端一致的编程体验,于是socket.io诞生。

socket.io设计的目标是支持任何的浏览器,任何Mobile设备。目前支持主流的PC浏览器(IE,Safari,Chrome,Firefox,Opera等),Mobile浏览器(iphone Safari/ipad Safari/android WebKit/WebOS WebKit等)。

socket.io基于node.js并简化了WebSocket API,统一了各种通信API。它支持:WebSocket, Flash Socket, AJAX long-polling, AJAX multipart streaming, Forever IFrame, JSONP polling。

socket.io解决了实时的通信问题,并统一了服务端与客户端的编程方式。启动了socket以后,就像建立了一条客户端与服务端的管道,两边可以互通有无。

安装

在命令行中执行:npm install socket.io 即可安装。

服务端编程模型

服务端编程还是与普通服务器一样,启动服务器,提供服务,处理事件。

比如下面的server.js:

var http = require('http') , url = require('url') , fs = require('fs') , server; server = http.createServer(function(req, res){ // your normal server code var path = url.parse(req.url).pathname; switch (path){ case 'https://www.jb51.net/': res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<h1>Hello! Try the <a href="https://www.jb51.net/index.html">Socket.io Test</a></h1>'); res.end(); break; case 'https://www.jb51.net/index.html': fs.readFile(__dirname + path, function(err, data){ if (err) return send404(res); res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'}) res.write(data, 'utf8'); res.end(); }); break; default: send404(res); } }), send404 = function(res){ res.writeHead(404); res.write('404'); res.end(); }; server.listen(8080); var io = require('socket.io').listen(server); io.sockets.on('connection', function(socket){ console.log("Connection " + socket.id + " accepted."); socket.on('message', function(message){ console.log("Received message: " + message + " - from client " + socket.id); }); socket.on('disconnect', function(){ console.log("Connection " + socket.id + " terminated."); }); });

客户端编程模型 

客户端编程也是相似的处理方式,连接服务器,交互信息。

比如下面的index.html页面:

<!doctype html> <html> <head> <title>Socket.io Test</title> <script src="https://www.jb51.net/json.js"></script> <!-- for ie --> <script src="https://www.jb51.net/socket.io/socket.io.js"></script> </head> <body> <script> var socket; var firstconnect = true; function connect() { if(firstconnect) { socket = io.connect(null); socket.on('message', function(data){ message(data); }); socket.on('connect', function(){ status_update("Connected to Server"); }); socket.on('disconnect', function(){ status_update("Disconnected from Server"); }); socket.on('reconnect', function(){ status_update("Reconnected to Server"); }); socket.on('reconnecting', function( nextRetry ){ status_update("Reconnecting in " + nextRetry + " seconds"); }); socket.on('reconnect_failed', function(){ message("Reconnect Failed"); }); firstconnect = false; } else { socket.socket.reconnect(); } } function disconnect() { socket.disconnect(); } function message(data) { document.getElementById('message').innerHTML = "Server says: " + data; } function status_update(txt){ document.getElementById('status').innerHTML = txt; } function esc(msg){ return msg.replace(/</g, '&lt;').replace(/>/g, '&gt;'); } function send() { socket.send("Hello Server!"); }; </script> <h1>Socket.io Test</h1> <div><p>Waiting for input</p></div> <div><p></p></div> <button/>Connect</button> <button>Disconnect</button> <button/>Send Message</button> </body> </html>

注意事项

1. 启动服务器还是交给node,打开命令行窗口,定位到server.js所在文件夹,输入node server.js启动服务器。

在上面的index.html中,注意这行:<script src="https://www.jb51.net/socket.io/socket.io.js"></script>。如果不想使用本地的socket.io脚本,可

以直接使用下面这个公开的脚本:

<script src="https://cdn.socket.io/stable/socket.io.js"></script>

此外需要注意这行:socket = io.connect(null)。

这里的null代表连接本地服务,可以换成"localhost",效果也是一样的。

2. 可以使用socket.io直接启动http服务。

例如:

var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { io.sockets.emit('this', { will: 'be received by everyone'}); });

3. socket.io可以直接通过send方法发送消息,使用message事件接收消息,例如:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wggxdz.html