分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

websocket 实战

发布时间:2023-09-06 01:47责任编辑:郭大石关键词:websocket

1.WebSocket protocol 是HTML5一种新的协议。它是实现了浏览器与服务器全双工通信(full-duplex)。HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽并达到实时通讯。

在WebSocket出现之前,一般通过两种方式来实现Web实时用:轮询机制和流技术;其中轮询有不同的轮询,还有一种叫Comet的长轮询。

轮询:这是最早的一种实现实时 Web 应用的方案。客户端以一定的时间间隔向服务端发出请求,以频繁请求的方式来保持客户端和服务器端的同步。这种同步方案的缺点是,当客户端以固定频率向服务 器发起请求的时候,服务器端的数据可能并没有更新,这样会带来很多无谓的网络传输,所以这是一种非常低效的实时方案。

长轮询:是对定时轮询的改进和提高,目地是为了降低无效的网络传输。当服务器端没有数据更新的时候,连接会保持一段时间周期直到数据或状态改变或者 时间过期,通过这种机制来减少无效的客户端和服务器间的交互。当然,如果服务端的数据变更非常频繁的话,这种机制和定时轮询比较起来没有本质上的性能的提 高。

流:常就是在客户端的页面使用一个隐藏的窗口向服务端发出一个长连接的请求。服务器端接到这个请求后作出回应并不断更新连接状态以保证客户端和服务 器端的连接不过期。通过这种机制可以将服务器端的信息源源不断地推向客户端。这种机制在用户体验上有一点问题,需要针对不同的浏览器设计不同的方案来改进 用户体验,同时这种机制在并发比较大的情况下,对服务器端的资源是一个极大的考验。

2.前端

JavaScript调用浏览器接口实例如下:

var wsServer = ‘ws://localhost:8888/Demo‘; //服务器地址var websocket = new WebSocket(wsServer); //创建WebSocket对象websocket.send("hello");//向服务器发送消息alert(websocket.readyState);//查看websocket当前状态websocket.onopen = function (evt) { ?//已经建立连接};websocket.onclose = function (evt) { ?//已经关闭连接};websocket.onmessage = function (evt) { ?//收到服务器消息,使用evt.data提取};websocket.onerror = function (evt) { ?//产生异常}; 

3.后端

握手协议的客户端数据已经由浏览器代劳了,服务器端需要我们自己来实现,目前市场上开源的实现也比较多如:

Kaazing WebSocket Gateway(一个 Java 实现的 WebSocket Server);
?mod_pywebsocket(一个 Python 实现的 WebSocket Server);
?Netty(一个 Java 实现的网络框架其中包括了对 WebSocket 的支持);
?node.js(一个 Server 端的 JavaScript 框架提供了对 WebSocket 的支持);
?WebSocket4Net(一个.net的服务器端实现);

实例代码如下:

/// <summary>/// 生成Sec-WebSocket-Accept/// </summary>/// <param name="handShakeText">客户端握手信息</param>/// <returns>Sec-WebSocket-Accept</returns>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);}

4.小结

客户端:

<html><head> ?<meta charset="UTF-8"> ?<title>Web sockets test</title> ?<script src="jquery-min.js" type="text/javascript"></script> ?<script 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); ???} ?</script></head><body> ?<button id=‘ToggleConnection‘ type="button" onclick=‘ToggleConnectionClicked();‘>连接服务器</button> ?<br /> ?<button id=‘ToggleConnection‘ type="button" onclick=‘SendData();‘>发送我的名字:beston</button> ?<br /> ?<button id=‘ToggleConnection‘ type="button" onclick=‘seestate();‘>查看状态</button></body></html>

服务端:

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()); ?????} ???} ????/// <summary> ???/// 打包握手信息 ???/// </summary> ???/// <param name="secKeyAccept">Sec-WebSocket-Accept</param> ???/// <returns>数据包</returns> ???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()); ???} ????/// <summary> ???/// 生成Sec-WebSocket-Accept ???/// </summary> ???/// <param name="handShakeText">客户端握手信息</param> ???/// <returns>Sec-WebSocket-Accept</returns> ???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); ???} ????/// <summary> ???/// 解析客户端数据包 ???/// </summary> ???/// <param name="recBytes">服务器接收的数据包</param> ???/// <param name="recByteLength">有效数据长度</param> ???/// <returns></returns> ???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); ???} ?????/// <summary> ???/// 打包服务器数据 ???/// </summary> ???/// <param name="message">数据</param> ???/// <returns>数据包</returns> ???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; ???} ?}}

.

websocket 实战

原文地址:https://www.cnblogs.com/crazycode2/p/8685865.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved