什么是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;