【转】WebSocket初探
生活随笔
收集整理的這篇文章主要介紹了
【转】WebSocket初探
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義:
遵循RFC6544協議的通信協議。Webcoket協議和http協議屬于并行關系,但是websocket是以http協議為基礎開發出來的(微軟用IhttpHandler接口中同時處理這兩種協議),同時他們都是以TCP協議為基礎。可以進行雙向通信、持久化通信。Http是單向通信協議、無狀態通信。
websocket協議(握手部分):
GET /chat HTTP/1.1Host: http://server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin:?http://example.com
比http握手多了幾個部分:
Upgrade: websocketConnection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
這幾個部分告訴服務器,該請求是Webcoket,不是http了。
接收的數據
GET /chat HTTP/1.1Host:?http://example.com:8000
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
發送的數據
HTTP/1.1 101 Switching ProtocolsUpgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
?
服務端:
- 使用第三方的Fleck庫,建議采用吧,比較方便。
- 使用第三方的websocketsharp庫,不方便服務端主動推送數據到客戶端。
- 自己按照RFC6544協議,打包協議頭+socket API庫,收發數據。
- 使用IIS8.0以上可以處理websocket請求:
- 使用TcpListener類庫,不能使用httpListener類庫,,創建監聽,并將發送的數據按RFC6544協議打包。
class Server {
public static void Main() {
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
}
}
(接收數據)
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("A client connected.");
NetworkStream stream = client.GetStream();
while(client.Available < 3)
{
// wait for enough bytes to be available
}
//enter to an infinite cycle to be able to handle every change in stream
while (true) {
while (!stream.DataAvailable);
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
}
(打包發送的數據)
if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data))
{
const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
+ "Connection: Upgrade" + eol
+ "Upgrade: websocket" + eol
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
System.Security.Cryptography.SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + eol
+ eol);
stream.Write(response, 0, response.Length);
}
客戶端:
- html5的JS庫
- Fleck庫
- websocketsharp庫
- 微軟自己的wensocketclient庫
- 自己按照RFC6544協議,打包協議頭+socket API庫,收發數據
總結
以上是生活随笔為你收集整理的【转】WebSocket初探的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#语言之“string格式的日期时间字
- 下一篇: 再见!罗永浩微博正式更名交个朋友直播间