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

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

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

var ws;

function ToggleConnectionClicked() {

try {

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

ws.onopen = function(event){alert("已經與服務器建立了連接rn當前連接狀態:"+this.readyState);};

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

ws.onclose = function(event){alert("已經與服務器斷開連接rn當前連接狀態:"+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);

}

連接服務器

發送我的名字:beston

查看狀態

服務器端代碼:

代碼如下復制代碼

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();//接受一個連接

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

//握手

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

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

Console.WriteLine("已經發送握手協議了....");

//接受客戶端數據

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

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

string clientMsg=AnalyticData(buffer, length);

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

//發送數據

string sendMsg = "您好," + clientMsg;

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

sc.Send(PackData(sendMsg));

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

}

catch (Exception e)

{

Console.WriteLine(e.ToString());

}

}

///

/// 打包握手信息

///

/// Sec-WebSocket-Accept

/// 數據包

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協議,但居然握手不成功,目前仍沒弄明白!

//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);

}

///

/// 解析客戶端數據包

///

/// 服務器接收的數據包

/// 有效數據長度

///

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; // 數據長度

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);

}

///

/// 打包服務器數據

///

/// 數據

/// 數據包

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{

// 暫不處理超長內容

}

return contentBytes;

}

}

}

運行效果:

使用的瀏覽器:

疑問:如實例中

代碼如下復制代碼

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

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

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

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

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

連接鍵盤 功能

什么是”連接鍵盤“功能

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

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

WebSocket-Server里項目含義如下:

Mobile:手機模擬器,與手機通訊服務器進行UDP通訊,負責提示打開的頁面地址,并輸入GUID(相當于二維碼)與頁面進行綁定;

MobileServer:手機通訊服務器,負責接收手機信息(比如微信的賬戶信息以及二維碼信息),此處接收GUID。并轉發至WebSocket通訊服務器;

WebSocket:WebSocket通訊服務器,與手機通訊服務器和頁面的WebSocket進行通訊;

WebSocket-Client里項目含義如下:

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

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

實現原理

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

注意事項

如果自己測試請根據上述步驟先啟動手機通訊服務器和WebSocket通訊服務器;

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

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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