寫websocket客戶端應用程序
WebSocke是一個基於ws協議的技術,它可以實現在客戶端和服務器端簡歷長久連接,
一個典型的websocket了客戶端是用戶的瀏覽器,但是這個協議是跨平臺的,不受應用限制
創建一個websocket對象
你需要創建一個websocket對象來實現通過websocket協議的通信,對象會自動建立與服務器的連接
1 2 3 4
|
WebSocket WebSocket( in DOMString url, in optional DOMString protocols );
|
url
URL是所要連接的地址,請求這個地址會得到websocket服務器的響應
protocols 可選參數
可以是單個協議,也可以是多個協議組成數組的形式,這些字符串表明其子協議,這樣單個服務器可以實現多個websocket子協議(例如,你想讓單個服務器基於具體的協議來處理不同的互動類型),如果你沒有聲明一個協議字符串,默認取空字符串
Connection errors
當嘗試連接的時候出現錯誤,首先一個簡單的“error”事件將被髮送給websocket對象(從而會調用onerror事件處理器),然後會“closeEvent”事件將被髮送給websocket對象(從而會調用onclose事件處理器)來表明連接關閉的原因。
Examples
這個簡單的例子創建了一個websocket連接到位於“ws://www.example.com/socketserver”的服務器,通常,第二個參數protocol寫爲“protocolOne”,這個參數也可以省略。
1
|
var exampleSocket = new WebSocket("ws://www.example.com/socketserver", "protocolOne");
|
作爲返回,exampleSocket.readyState被置爲CONNECTING,一旦連接準備好去傳輸數據,exampleSocket.readyState就被置爲OPEN
如果你想建立一個連接,靈活支持你支持的協議,那麼可以給第二個參數傳入一個協議數組
1
|
var exampleSocket = new WebSocket("ws://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
|
一旦連接被創建,exampleSocket.protocol將告訴你服務器選擇的是哪種協議
在上面的示例中ws協議替代http協議,相類似的,wss協議替代https協議
Sending data to the server
ws連接建立好了,你就可以向服務器發送數據,可以使用websocket的send方法來發送數據
1
|
exampleSocket.send("Here's some text that the server is urgently awaiting!");
|
你可發送string, blob, ArrayBuffer格式的數據
note: firefox11之前的版本只支持發送字符串
由於創建一個連接是易步的且容易失敗,所以不能保證在創建了websocket對象之後立即調用send()方法會成功,我們可以保證可以在onopen事件處理器被定義之後去嘗試發送數據
1 2 3
|
exampleSocket.onopen = function (event) { exampleSocket.send("Here's some text that the server is urgently awaiting!"); };
|
Using JSON to transmit objects
我們可以使用json來方便的傳輸較複雜的數據
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// Send text to all users through the server function sendText() { // Construct a msg object containing the data the server needs to process the message from the chat client. var msg = { type: "message", text: document.getElementById("text").value, id: clientID, date: Date.now() }; // Send the msg object as a JSON-formatted string. exampleSocket.send(JSON.stringify(msg)); // Blank the text input element, ready to receive the next line of text from the user. document.getElementById("text").value = ""; }
|
Receiving messages from the server
WebSockets 是一個時間驅動的API,當收到一個消息,message事件就會被傳遞個onmessage函數,來監聽收到的數據,你可以這樣做
1 2 3
|
exampleSocket.onmessage = function (event) { console.log(event.data); }
|
Receiving and interpreting JSON objects
客戶端可能會收到各種類型的數據,例如:
-登陸握手
-消息文本
-用戶列表更新
解譯收到的數據的代碼應該如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
exampleSocket.onmessage = function(event) { var f = document.getElementById("chatbox").contentDocument; var text = ""; var msg = JSON.parse(event.data); var time = new Date(msg.date); var timeStr = time.toLocaleTimeString(); switch(msg.type) { case "id": clientID = msg.id; setUsername(); break; case "username": text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>"; break; case "message": text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>"; break; case "rejectusername": text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>" break; case "userlist": var ul = ""; for (i=0; i < msg.users.length; i++) { ul += msg.users[i] + "<br>"; } document.getElementById("userlistbox").innerHTML = ul; break; } if (text.length) { f.write(text); document.getElementById("chatbox").contentWindow.scrollByPages(1); } };
|
這裏我們使用JSON.parse()把json字符串轉化爲json對象,然後再按代碼執行
文本數據格式
通過websocket連接收到的數據都是utf-8編碼的
關閉連接
當你想停止使用websocket連接,可以調用websocket對象的close()方法
1
|
exampleSocket.close();
|
安全考慮
websocket不應該在混合環境下使用,這就是,你不能在通過HTTPS 或者 vice-versa加載的頁面來簡歷非安全的websocket連接,事實上,一些瀏覽器明確的禁止這樣做,包括firefox8及後續版本
注:翻譯自火狐開發者文檔