WebSocket使用教程 - 帶完整實(shí)例(收藏)

什么是WebSocket?看過html5的同學(xué)都知道,WebSocket protocol 是HTML5一種新的協(xié)議。它是實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工通信(full-duplex)。HTML5定義了WebSocket協(xié)議,能更好的節(jié)省服務(wù)器資源和帶寬并達(dá)到實(shí)時(shí)通訊?,F(xiàn)在我們來探討一下html5的WebSocket

jquery-min.js" type="text/javascript">

var ws;

function ToggleConnectionClicked() {

try {

ws = new WebSocket("ws://10.9.146.31:1818/chat");//連接服務(wù)器

ws.onopen = function(event){alert("已經(jīng)與服務(wù)器建立了連接rn當(dāng)前連接狀態(tài):"+this.readyState);};

ws.onmessage = function(event){alert("接收到服務(wù)器發(fā)送的數(shù)據(jù):rn"+event.data);};

ws.onclose = function(event){alert("已經(jīng)與服務(wù)器斷開連接rn當(dāng)前連接狀態(tài):"+this.readyState);};

ws.onerror = function(event){alert("WebSocket異常!");};

}catch(ex) {

alert(ex.message);

}

};

function SendData() {

try{

ws.send("beston");

}catch(ex){

alert(ex.message);

}

};

function seestate(){

alert(ws.readyState);

}

連接服務(wù)器

發(fā)送我的名字:beston

查看狀態(tài)

服務(wù)器端代碼:

代碼如下復(fù)制代碼

using System;

using System.Net;

using System.Net.Sockets;

using System.Security.Cryptography;

using System.Text;

using System.Text.RegularExpressions;

namespace WebSocket

{

class Program

{

static void Main(string[] args)

{

int port = 1818;

byte[] buffer = new byte[1024];

IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);

Socket listener = new Socket(localEP.Address.AddressFamily,SocketType.Stream, ProtocolType.Tcp);

try{

listener.Bind(localEP);

listener.Listen(10);

Console.WriteLine("等待客戶端連接....");

Socket sc = listener.Accept();//接受一個(gè)連接

Console.WriteLine("接受到了客戶端:"+sc.RemoteEndPoint.ToString()+"連接....");

//握手

int length = sc.Receive(buffer);//接受客戶端握手信息

sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer,length)));

Console.WriteLine("已經(jīng)發(fā)送握手協(xié)議了....");

//接受客戶端數(shù)據(jù)

Console.WriteLine("等待客戶端數(shù)據(jù)....");

length = sc.Receive(buffer);//接受客戶端信息

string clientMsg=AnalyticData(buffer, length);

Console.WriteLine("接受到客戶端數(shù)據(jù):" + clientMsg);

//發(fā)送數(shù)據(jù)

string sendMsg = "您好," + clientMsg;

Console.WriteLine("發(fā)送數(shù)據(jù):“"+sendMsg+"” 至客戶端....");

sc.Send(PackData(sendMsg));

Console.WriteLine("演示Over!");

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

///

/// 打包握手信息

///

/// Sec-WebSocket-Accept

/// 數(shù)據(jù)包

private static byte[] PackHandShakeData(string secKeyAccept)

{

var responseBuilder = new StringBuilder();

responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);

responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);

responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);

responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);

//如果把上一行換成下面兩行,才是thewebsocketprotocol-17協(xié)議,但居然握手不成功,目前仍沒弄明白!

//responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);

//responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);

return Encoding.UTF8.GetBytes(responseBuilder.ToString());

}

///

/// 生成Sec-WebSocket-Accept

///

/// 客戶端握手信息

/// Sec-WebSocket-Accept

private static string GetSecKeyAccetp(byte[] handShakeBytes,int bytesLength)

{

string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);

string key = string.Empty;

Regex r = new Regex(@"Sec-WebSocket-Key:(.*?)rn");

Match m = r.Match(handShakeText);

if (m.Groups.Count != 0)

{

key = Regex.Replace(m.Value, @"Sec-WebSocket-Key:(.*?)rn", "$1").Trim();

}

byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));

return Convert.ToBase64String(encryptionString);

}

///

/// 解析客戶端數(shù)據(jù)包

///

/// 服務(wù)器接收的數(shù)據(jù)包

/// 有效數(shù)據(jù)長度

///

private static string AnalyticData(byte[] recBytes, int recByteLength)

{

if (recByteLength < 2) { return string.Empty; }

bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最后一幀

if (!fin){

return string.Empty;// 超過一幀暫不處理

}

bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩碼

if (!mask_flag){

return string.Empty;// 不包含掩碼的暫不處理

}

int payload_len = recBytes[1] & 0x7F; // 數(shù)據(jù)長度

byte[] masks = new byte[4];

byte[] payload_data;

if (payload_len == 126){

Array.Copy(recBytes, 4, masks, 0, 4);

payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]);

payload_data = new byte[payload_len];

Array.Copy(recBytes, 8, payload_data, 0, payload_len);

}else if (payload_len == 127){

Array.Copy(recBytes, 10, masks, 0, 4);

byte[] uInt64Bytes = new byte[8];

for (int i = 0; i < 8; i++){

uInt64Bytes[i] = recBytes[9 - i];

}

UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0);

payload_data = new byte[len];

for (UInt64 i = 0; i < len; i++){

payload_data[i] = recBytes[i + 14];

}

}else{

Array.Copy(recBytes, 2, masks, 0, 4);

payload_data = new byte[payload_len];

Array.Copy(recBytes, 6, payload_data, 0, payload_len);

}

for (var i = 0; i < payload_len; i++){

payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]);

}

return Encoding.UTF8.GetString(payload_data);

}

///

/// 打包服務(wù)器數(shù)據(jù)

///

/// 數(shù)據(jù)

/// 數(shù)據(jù)包

private static byte[] PackData(string message)

{

byte[] contentBytes = null;

byte[] temp = Encoding.UTF8.GetBytes(message);

if (temp.Length < 126){

contentBytes = new byte[temp.Length + 2];

contentBytes[0] = 0x81;

contentBytes[1] = (byte)temp.Length;

Array.Copy(temp, 0, contentBytes, 2, temp.Length);

}else if (temp.Length < 0xFFFF){

contentBytes = new byte[temp.Length + 4];

contentBytes[0] = 0x81;

contentBytes[1] = 126;

contentBytes[2] = (byte)(temp.Length & 0xFF);

contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);

Array.Copy(temp, 0, contentBytes, 4, temp.Length);

}else{

// 暫不處理超長內(nèi)容

}

return contentBytes;

}

}

}

運(yùn)行效果:

使用的瀏覽器:

疑問:如實(shí)例中

代碼如下復(fù)制代碼

responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);

//如果把上一行換成下面兩行,才是thewebsocketprotocol-17協(xié)議,但居然握手不成功,目前仍沒弄明白!

//responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);

//responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);

這是為什么呢?看到這篇博文的兄弟希望能夠給我解惑!

連接鍵盤 功能

什么是”連接鍵盤“功能

”連接鍵盤“功能其實(shí)就是開通了網(wǎng)頁版的微信,利用鍵盤可以快速錄入文字聊天。

連接方法很簡單,用手機(jī)打開微信點(diǎn)擊右上角魔術(shù)棒,會(huì)彈出三個(gè)選項(xiàng),只用選擇連接鍵盤就可以了,這時(shí)用瀏覽器打開wx.qq.com然后用手機(jī)掃描網(wǎng)頁中的二維碼即可打開網(wǎng)頁版微信,而這時(shí)也就可以直接利用電腦鍵盤實(shí)現(xiàn)快速聊天了。

WebSocket-Server里項(xiàng)目含義如下:

Mobile:手機(jī)模擬器,與手機(jī)通訊服務(wù)器進(jìn)行UDP通訊,負(fù)責(zé)提示打開的頁面地址,并輸入GUID(相當(dāng)于二維碼)與頁面進(jìn)行綁定;

MobileServer:手機(jī)通訊服務(wù)器,負(fù)責(zé)接收手機(jī)信息(比如微信的賬戶信息以及二維碼信息),此處接收GUID。并轉(zhuǎn)發(fā)至WebSocket通訊服務(wù)器;

WebSocket:WebSocket通訊服務(wù)器,與手機(jī)通訊服務(wù)器和頁面的WebSocket進(jìn)行通訊;

WebSocket-Client里項(xiàng)目含義如下:

test.html:測試的web頁面(類似微信的wx.qq.com);

jquery-1.8.0.min.js:jquery框架;

實(shí)現(xiàn)原理

頁面test.html生成GUID并存儲(chǔ)在WebSocket,手機(jī)模擬器輸入GUID并傳至WebSocket服務(wù)器,在WebSocket服務(wù)器檢索頁面Socket信息并通訊。

注意事項(xiàng)

如果自己測試請(qǐng)根據(jù)上述步驟先啟動(dòng)手機(jī)通訊服務(wù)器和WebSocket通訊服務(wù)器;

把所有是“10.9.146.31”的字符串更換為自己的IP;

原文地址:http://www.111cn.net/wy/html5/69508.htm

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • <!DOCTYPE html> 查看源 window.WRM=window.WRM||{};window....
    SMSM閱讀 927評(píng)論 1 0
  • 原文在:http://www.king-liu.net, 歡迎大家來 WebSocket protocol 是HT...
    lkinga7閱讀 3,720評(píng)論 0 17
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,715評(píng)論 19 139
  • 提筆畫江山,山河蕩我心,誰料一席夢(mèng),浮生半片山,眾矢萬難艱,浪人仍依舊。
    畫個(gè)夢(mèng)閱讀 225評(píng)論 0 0
  • 理論 在Apple的文檔中,scheme在URL相關(guān)的內(nèi)容中出現(xiàn)過,比如: 緊接著這一段,有如下說明: 詳情點(diǎn)擊這...
    Mr_Zander閱讀 6,922評(píng)論 4 4

友情鏈接更多精彩內(nèi)容