首页 > 编程语言 >html5 的 webScoket 和 C# 建立Socket连接

html5 的 webScoket 和 C# 建立Socket连接

时间:2023-09-18 09:44:22浏览次数:45  
标签:WebSocket Socket C# var html5 msg new byte payload

html5 的 webScoket 和 C# 建立Socket连接

最近使用的web项目中,需要服务器直接触发前端显示效果。

所以研究了一下websocket:

名词解释:

WebSocket
WebSocket协议是一种双向通信协议,它建立在TCP之上,同http一样通过TCP来传输数据,但是它和http最大的不同有两点:


1.WebSocket是一种双向通信协议,在建立连接后,WebSocket服务器和Browser/UA都能主动的向对方发送或接收数据,就像Socket一样,不同的是WebSocket是一种建立在Web基础上的一种简单模拟Socket的协议;


2.WebSocket需要通过握手连接,类似于TCP它也需要客户端和服务器端进行握手连接,连接成功后才能相互通信。
当Web应用程序调用new WebSocket(url)接口时,Browser就开始了与地址为url的WebServer建立握手连接的过程。

 

客户端向服务器发送请求:
GET /chat HTTP/1.1  
Host: server.example.com  
Upgrade: websocket  
Connection: Upgrade  
Sec-WebSocket-Key:dGhlIHNhbXBsZSBub25jZQ==  
Origin: http://example.com  
Sec-WebSocket-Protocol: chat,superchat  
Sec-WebSocket-Version: 13 

服务器端返回内容:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: xsOSgr30aKL2GNZKNHKmeT1qYjA=


请求中的【Sec-WebSocket-Key】是随机发送的。而服务器返回的【Sec-WebSocket-Accept】是将【Sec-WebSocket-Key】加上一个固定字符串【258EAFA5-E914-47DA-95CA-C5AB0DC85B11】,并使用SHA-1加密后,再进行BASE-64编码生成的。

 

 

一个简单的DEMO:

前端页面:

 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 <!DOCTYPE html> <html> <head>     <title>Web Socket Client</title> </head> <body style="padding:10px;">     <h1>聊天室</h1>     <div style="margin:5px 0px;">         Address:         <div><input id="address" type="text" value="ws://127.0.0.1:1818" style="width:400px;" /></div>     </div>     <div style="margin:5px 0px;">         Name:         <div><input id="name" type="text" value="Byron" style="width:400px;" /></div>     </div>     <div>         <button id="connect" onclick="connect();">connect server</button> &nbsp;&nbsp;         <button id="disconnect" onclick="quit();">disconnect</button>&nbsp;&nbsp;         <button id="clear" onclick="clearMsg();">clear</button>     </div>     <h5 style="margin:4px 0px;">Message:</h5>     <div id="message" style="border:solid 1px #333; padding:4px; width:400px; overflow:auto;           height:300px; margin-bottom:8px; font-size:14px;">     </div>     <input id="text" type="text" onkeypress="enter(event);" style="width:340px" /> &nbsp;&nbsp;     <button id="send" onclick="send();">send</button>       <script type="text/javascript">         var name=document.getElementById('name').value;         var msgContainer=document.getElementById('message');         var text=document.getElementById('text');           function connect () {             var address=document.getElementById('address').value;               ws=new WebSocket(address);             ws.onopen=function(e){                 var msg=document.createElement('div');                 msg.style.color='#0f0';                 msg.innerHTML="Server > connection open.";                 msgContainer.appendChild(msg);                 ws.send('{'+document.getElementById('name').value+'}');             };             ws.onmessage=function(e){                 var msg=document.createElement('div');                 msg.style.color='#fff';                 msg.innerHTML=e.data;                 msgContainer.appendChild(msg);             };             ws.onerror=function(e){                 var msg=document.createElement('div');                 msg.style.color='#0f0';                 msg.innerHTML='Server > '+e.data;                 msgContainer.appendChild(msg);             };             ws.onclose=function(e){                 var msg=document.createElement('div');                 msg.style.color='#0f0';                 msg.innerHTML="Server > connection closed by server.";                 msgContainer.appendChild(msg);             };             text.focus();         }           function quit(){             if(ws){                 ws.close();                 var msg=document.createElement('div');                 msg.style.color='#0f0';                 msg.innerHTML='Server > connection closed.';                 msgContainer.appendChild(msg);                 ws=null;             }         }           function send(){             ws.send(text.value);             setTimeout(function(){                 msgContainer.scrollTop=msgContainer.getBoundingClientRect().height;             },100);             text.value='';             text.focus();         }           function clearMsg(){             msgContainer.innerHTML="";         }           function enter(event){             if(event.keyCode==13){              send();             }         }     </script> </body> </html>

  

后台代码(C#): 

 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 class Program     {           private static Socket listener;         private static Hashtable ht;         static void Main(string[] args)         {             int port = 1818;//监听端口为1818端口             ht = new Hashtable();//用于存放客户端的连接socket             byte[] buffer = new byte[1024];               var localEP = new IPEndPoint(IPAddress.Any, port);             listener = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);               try             {                 listener.Bind(localEP);                 listener.Listen(10);                   Console.WriteLine("等待客户端连接....");                 while (true)                 {                     Socket clientSocket = listener.Accept(); //接收到客户端的连接                          var th = new Thread(new ParameterizedThreadStart(Receive));                     th.Start(clientSocket);                 }             }             catch (Exception e)             {                 Console.WriteLine(e.ToString());             }         }         /// <summary>         /// 线程调用         /// </summary>         private static void Receive(object o)//Socket clientSocket)         {             Socket clientSocket = (Socket)o;             clientSocket.Blocking = true;             IPEndPoint clientipe = (IPEndPoint)clientSocket.RemoteEndPoint;             //    Console.WriteLine("[" + clientipe.Address.ToString() + "] Connected");             var key = string.Format("{0}-X-Q-X-{1}", clientipe.Address.ToString(), clientipe.Port);             if (!ht.ContainsKey(key))             {                 //将ip地址设置为hashTable的key值 若hashTable中存在该ip地址则不再ht中添加socket以免发送重复数据                 ht.Add(key, clientSocket);             }             Console.WriteLine("接收到了客户端:ip" + clientSocket.RemoteEndPoint.ToString() + "的连接");             byte[] buffer = new byte[1024];             int length = clientSocket.Receive(buffer);             clientSocket.Send(PackHandShakeData(GetSecKeyAccetp(buffer, length)));             Console.WriteLine("已经发送握手协议了....");               //接收用户姓名信息             length = clientSocket.Receive(buffer);             string xm = AnalyticData(buffer, length);               clientSocket.Send(PackData("连接时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));                   try             {                   while (true)                 {                     var errLs = new List<object>();                     //接受客户端数据                     Console.WriteLine("等待客户端数据....");                     try                     {                         length = clientSocket.Receive(buffer);//接受客户端信息                     }                     catch (SocketException e)                     {                         //去除字典                         Console.WriteLine(e.Message);                         try                         {                             foreach (DictionaryEntry de in ht)                             {                                 if (de.Value == clientSocket)                                 {                                     ht.Remove(de.Key);                                 }                             }                         }                         catch (Exception ex)                         {                             Console.WriteLine(ex.Message);                         }                                               }                     string clientMsg = AnalyticData(buffer, length);                     Console.WriteLine("接受到客户端数据:" + clientMsg);                       //发送数据                     string sendMsg = "" + clientMsg;                     Console.WriteLine("发送数据:“" + sendMsg + "” 至客户端....");                     //遍历hashTable中的数据获取Socket发送数据                     foreach (DictionaryEntry de in ht)                     {                         try                         {                             var sc = (Socket)de.Value;                             sc.Send(PackData(clientSocket.RemoteEndPoint.ToString() + xm + "说:" + sendMsg));                         }                         catch (Exception e)                         {                             Console.WriteLine("Num:{0} err:{1}", ht.Count, e);                             errLs.Add(de.Key);                         }                     }                       if (errLs != null && errLs.Any())                     {                         foreach (var item in errLs)                         {                             ht.Remove(item);                         }                     }                       Thread.Sleep(1000);                 }             }             catch (SocketException e)             {                 //去除字典                 Console.WriteLine(e.Message);             }             catch (System.ObjectDisposedException e)             {                 //去除字典                 Console.WriteLine(e.Message);             }             catch (Exception e)             {                 Console.WriteLine(e.Message);             }             }         /// <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:(.*?)\r\n");             Match m = r.Match(handShakeText);             if (m.Groups.Count != 0)             {                 key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$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;         }     }

 

运行效果:

 本文引用:http://xqblog.top/Article.aspx?id=ART2018080900001

标签:WebSocket,Socket,C#,var,html5,msg,new,byte,payload
From: https://www.cnblogs.com/sexintercourse/p/17710801.html

相关文章

  • HCIP-交换-生成树协议
    BUM帧(Broadcast,Unknownunicast,Multicast)制定广播、未知单播及组播帧。stpdisable禁用生成树。STP生成树协议STP概述作用:保证网络可靠性的前提下,解决二层环路带来的风险。二层环路带来的风险:广播风暴MAC地址漂移STP遵循的协议:IEEE802.1d工作原理:STP通过交互......
  • 每天一个linux命令(48):watch命令
    watch是一个非常实用的命令,基本所有的Linux发行版都带有这个小工具,如同名字一样,watch可以帮你监测一个命令的运行结果,省得你一遍遍的手动运行。在Linux下,watch是周期性的执行下个程序,并全屏显示执行结果。你可以拿他来监测你想要的一切命令的结果变化,比如 tail 一个 log 文件......
  • 每天一个linux命令(50)0:crontab命令
    前一天学习了 at 命令是针对仅运行一次的任务,循环运行的例行性计划任务,linux系统则是由 cron (crond) 这个系统服务来控制的。Linux 系统上面原本就有非常多的计划性工作,因此这个系统服务是默认启动的。另外, 由于使用者自己也可以设置计划任务,所以, Linux 系统也提供了......
  • 5.0 CRC32校验技术概述
    CRC校验技术是用于检测数据传输或存储过程中是否出现了错误的一种方法,校验算法可以通过计算应用与数据的循环冗余校验(CRC)检验值来检测任何数据损坏。通过运用本校验技术我们可以实现对特定内存区域以及磁盘文件进行完整性检测,并以此来判定特定程序内存是否发生了变化,如果发生变化......
  • 搭建CUDA、CUDNN、Pytorch环境(Windows10/11)
    摘要:搭建Windows系统下Cuda+CUDNN环境,注意C盘一定要大,建议1T+SSD参考:  https://blog.csdn.net/weixin_61164016/article/details/127564466  https://blog.csdn.net/qq_43308156/article/details/127479544  https://blog.csdn.net/weixin_45068330/article/details/121......
  • 每天一个linux命令(40):wc命令
    Linux系统中的wc(WordCount)命令的功能为统计指定文件中的字节数、字数、行数,并将统计结果显示输出。1.命令格式:wc [选项]文件...2.命令功能:统计指定文件中的字节数、字数、行数,并将统计结果显示输出。该命令统计指定文件中的字节数、字数、行数。如果没有给出文件名,则从标准......
  • TienChin 渠道管理-渠道导入
    ChannelController@PostMapping("/importTemplate")voidimportTemplate(HttpServletResponseresponse){ExcelUtil<Channel>util=newExcelUtil<>(Channel.class);util.importTemplateExcel(response,"渠道数据");}@Log(tit......
  • TienChin 渠道管理-渠道页面完善
    最后附上渠道管理的数据installSQL语句:INSERTINTOTienChin.tienchin_channel(channel_id,channel_name,status,remark,type,create_by,update_by,create_time,update_time,del_flag)VALUES(3,'小红书渠道',1,'小红书渠道',1,'qudao','qu......
  • ICCV 2023 | 超越SAM!EntitySeg:更少的数据,更高的分割质量!
    前言 在本文中,High-QualityEntitySegmentation对分割问题进行了全新的探索。本文转载自CVer仅用于学术分享,若侵权请联系删除欢迎关注公众号CV技术指南,专注于计算机视觉的技术总结、最新技术跟踪、经典论文解读、CV招聘信息。CV各大方向专栏与各个部署框架最全教程整理【CV......
  • TienChin 渠道管理-渠道搜索
    ChannelController@PreAuthorize("hasPermission('tienchin:channel:list')")@GetMapping("/list")TableDataInfolist(ChannelVOchannelVO){startPage();List<Channel>list=iChannelService.selectChannelList(channe......