突袭HTML5之WebSocket入门3 - 通信模型socket.io
為什么需要socket.io?
??? node.js提供了高效的服務端運行環(huán)境,但是由于瀏覽器端對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,統(tǒng)一了各種通信API。它支持:WebSocket,?Flash Socket,?AJAX long-polling,?AJAX multipart streaming,?Forever IFrame,?JSONP polling。 socket.io解決了實時的通信問題,并統(tǒng)一了服務端與客戶端的編程方式。啟動了socket以后,就像建立了一條客戶端與服務端的管道,兩邊可以互通有無。 安裝??? 在命令行中執(zhí)行: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?'/':
??????res.writeHead(200,?{'Content-Type':?'text/html'});
??????res.write('<h1>Hello!?Try?the?<a?href="/index.html">Socket.io?Test</a></h1>');
??????res.end();
??????break;
????case?'/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="/json.js"></script>?<!--?for?ie?-->
????<script?src="/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,?'<').replace(/>/g,?'>');
????}
????
????function?send()?{
??????socket.send("Hello?Server!");????
????};???????
????</script>
????
????<h1>Socket.io?Test</h1>
????<div><p?id="status">Waiting?for?input</p></div>
????<div><p?id="message"></p></div>??
????<button?id="connect"?onClick='connect()'/>Connect</button>
????<button?id="disconnect"?onClick='disconnect()'>Disconnect</button>
????<button?id="send"?onClick='send()'/>Send?Message</button>
??</body>
</html>
注意事項
1. 啟動服務器還是交給node,打開命令行窗口,定位到server.js所在文件夾,輸入node server.js啟動服務器。
??? 在上面的index.html中,注意這行:<script?src="/socket.io/socket.io.js"></script>。如果不想使用本地的socket.io腳本,可以直接使用下面這個公開的腳本:
<script?src="http://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方法發(fā)送消息,使用message事件接收消息,例如:
//server.jsvar?io?=?require('socket.io').listen(80);
io.sockets.on('connection',?function?(socket)?{
??socket.on('message',?function?()?{?});
});
//index.html
<script>
??var?socket?=?io.connect('http://localhost/');
??socket.on('connect',?function?()?{
????socket.send('hi');
????socket.on('message',?function?(msg)?{
??????//?my?msg
????});
??});
</script>
4. 發(fā)送和處理數(shù)據(jù)
??? 兩端可以互發(fā)事件,互發(fā)數(shù)據(jù),相互通信。發(fā)送事件的代碼為:socket.emit(action, data, function),其中action為事件的名稱,data為數(shù)據(jù),function為回調函數(shù);處理事件代碼為:socket.on(action,function),如果emit發(fā)送的時候有數(shù)據(jù)data,則function中參數(shù)包含了這個數(shù)據(jù)。socket.io除了發(fā)送和處理內置事件,如connect, disconnect, message。還允許發(fā)送和處理自定義事件,例如:?
//服務端:io.sockets.on('connection',?function?(socket)?{
??socket.emit('news',?{?hello:?'world'?});
??socket.on('my?other?event',?function?(data)?{
????console.log(data);
??});
});
//客戶端:
<script?src="/socket.io/socket.io.js"></script>
<script>
??var?socket?=?io.connect('http://localhost');
??socket.on('news',?function?(data)?{
????console.log(data);
????socket.emit('my?other?event',?{?my:?'data'?});
??});
</script>
5. 從上面可以看出來,發(fā)送數(shù)據(jù)的時候,send和emit是都可以使用的。只不過emit更是強化了自定義事件的處理。
6. 可以在服務端使用socket的get/set方法存儲客服端的相關數(shù)據(jù),例如:
//服務端var?io?=?require('socket.io').listen(80);
io.sockets.on('connection',?function?(socket)?{
??socket.on('set?nickname',?function?(name)?{
????socket.set('nickname',?name,?function?()?{?socket.emit('ready');?});
??});
??socket.on('msg',?function?()?{
????socket.get('nickname',?function?(err,?name)?{
??????console.log('Chat?message?by?',?name);
????});
??});
});
//客戶端
<script>
??var?socket?=?io.connect('http://localhost');
??socket.on('connect',?function?()?{
????socket.emit('set?nickname',?confirm('What?is?your?nickname?'));
????socket.on('ready',?function?()?{
??????console.log('Connected?!');
??????socket.emit('msg',?confirm('What?is?your?message?'));
????});
??});
</script>
7. 可以廣播消息,比如聊天室中給除了當前socket連接外的所有人發(fā)消息。
var?io?=?require('socket.io').listen(80);io.sockets.on('connection',?function?(socket)?{
??socket.broadcast.emit('user?connected');
});
8. 可以在同一次鏈接中,建立多個互相獨立的通道,而不是建立多次鏈接。這個官方叫法是“多個namespace”,比如官方的例子:
var?io?=?require('socket.io').listen(80);//Server
var?chat?=?io
??.of('/chat')
??.on('connection',?function?(socket)?{
????socket.emit('a?message',?{
????????that:?'only'
??????,?'/chat':?'will?get'
????});
????chat.emit('a?message',?{
????????everyone:?'in'
??????,?'/chat':?'will?get'
????});
??});
var?news?=?io
??.of('/news')
??.on('connection',?function?(socket)?{
????socket.emit('item',?{?news:?'item'?});
??});
//Client
<script>
??var?chat?=?io.connect('http://localhost/chat')
????,?news?=?io.connect('http://localhost/news');
??chat.on('connect',?function?()?{
????chat.emit('hi!');
??});
??news.on('news',?function?()?{
????news.emit('woot');
??});
</script>
?
socket.io的配置?
??? socket.io的配置很簡單,如果配置過express的話,你會發(fā)現(xiàn)它們幾乎是使用差不多的方式。先看個小例子:
var?io?=?require('socket.io').listen(80);io.configure('production',?function(){
??io.enable('browser?client?etag');
??io.set('log?level',?1);
??io.set('transports',?[
????'websocket'
??,?'flashsocket'
??,?'htmlfile'
??,?'xhr-polling'
??,?'jsonp-polling'
??]);
});
io.configure('development',?function(){
??io.set('transports',?['websocket']);
});
可以看到,socket.io使用configure, set, enable, disable進行配置。
1. 使用configure方法配置不同的運行環(huán)境下的行為;就是說在不同的環(huán)境下,啟用不同的配置選項。configure的第一個參數(shù)是運行環(huán)境,第二個參數(shù)是進行配置的function。運行環(huán)境典型的如production或者是development,當然這里可以使任意的字符串。如果configure的第一個參數(shù)省略的話,說明后面的配置是公用的,不管是什么環(huán)境下,都有效。
2. 配置好各種運行環(huán)境了,那么如何設置當前運行在那個環(huán)境下呢?這個是通過在命令行中修改環(huán)境變量NODE_ENV的值實現(xiàn)的。
3. 在configure的配置函數(shù)中,我們可以使用set, enable, disable設置相關選項。
4. 具體可以配置的項參考:https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO
實用參考
socket.io介紹:http://davidchambersdesign.com/getting-started-with-socket.io/
socket.io安裝和使用說明:http://socket.io/
socket.io Wiki:https://github.com/LearnBoost/Socket.IO/wiki
總結
以上是生活随笔為你收集整理的突袭HTML5之WebSocket入门3 - 通信模型socket.io的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Q-learning家族【强化学习】
- 下一篇: FFTW 和 CUFFT 的使用对比