- String str = new String(data, CHARSET);
- String[] arr = str.split("\r\n");
- String[] temp = arr[0].split(" ");
- Map
map = this.toMap(arr); - String base64 = generateWebSocketAccept((String)map.get("Sec-WebSocket-Key"));
- StringBuffer sb = new StringBuffer(200);
- sb.append(temp[2]).append(" 101 Switching Protocols\r\n");
- sb.append("Upgrade: websocket\r\n");
- sb.append("Connection: Upgrade\r\n");
- sb.append("Sec-WebSocket-Accept: ").append(base64).append("\r\n\r\n");
其中最重要的是最后几个换行不要丢,将字符串转成byte[]写给客户端即可
- public static String generateWebSocketAccept(String webSocketKey) {
- System.out.println(webSocketKey);
- try {
- String acc = webSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
- MessageDigest sh1 = MessageDigest.getInstance("SHA1");
- sh1.update(acc.getBytes(CHARSET), 0, acc.length());
- return Base64.getEncoder().encodeToString(sh1.digest());
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException("SHA-1 algorithm not found", e);
- }
- }
收到的掩码转换
- int i, j;
- for(i=0, j=0; i
- data[j] = (byte) (data[i] ^ masks[j % 4]);
- }
下面是服务器向客户端发送消息
- public byte[] doSend(String mess) throws IOException{
- byte[] rawData = mess.getBytes();
-
- int frameCount = 0;
- byte[] frame = new byte[10];
-
- frame[0] = (byte) 129;
-
- if(rawData.length <= 125){
- frame[1] = (byte) rawData.length;
- frameCount = 2;
- }else if(rawData.length >= 126 && rawData.length <= 65535){
- frame[1] = (byte) 126;
- int len = rawData.length;
- frame[2] = (byte)((len >> 8 ) & (byte)255);
- frame[3] = (byte)(len & (byte)255);
- frameCount = 4;
- }else{
- frame[1] = (byte) 127;
- int len = rawData.length;
- frame[2] = (byte)((len >> 56 ) & (byte)255);
- frame[3] = (byte)((len >> 48 ) & (byte)255);
- frame[4] = (byte)((len >> 40 ) & (byte)255);
- frame[5] = (byte)((len >> 32 ) & (byte)255);
- frame[6] = (byte)((len >> 24 ) & (byte)255);
- frame[7] = (byte)((len >> 16 ) & (byte)255);
- frame[8] = (byte)((len >> 8 ) & (byte)255);
- frame[9] = (byte)(len & (byte)255);
- frameCount = 10;
- }
-
- int bLength = frameCount + rawData.length;
-
- byte[] reply = new byte[bLength];
-
- int bLim = 0;
- for(int i=0; i
- reply[bLim] = frame[i];
- bLim++;
- }
- for(int i=0; i
- reply[bLim] = rawData[i];
- bLim++;
- }
-
- return reply;
-
- }
-
相关阅读:
什么是云原生?土生土长?
【Nginx38】Nginx学习:SSL模块(二)错误状态码、变量及宝塔配置分析
[LeetCode] 最后一个单词的长度【58】
Python 潮流周刊#24:no-GIL 提案正式被采纳了!
😀 Java并发 - (并发基础)
【Nacos】1.1 从单体架构到微服务
git学习笔记
Node.js躬行记(21)——花10分钟入门Node.js
Spock单元测试框架介绍及在美团优选的实践_第二章(static静态方法mock方式)
苹果电脑怎么清理垃圾和缓存文件,mac如何清理系统缓存文件
-
原文地址:https://blog.csdn.net/zml_moxueli/article/details/132880594
-
最新文章
-
沪漂五周年了:我越来越迷茫了
Agentic Skill Routing 实战:别再把所有 Skill 塞进 AI Agent 上下文
MySQL-Seconds_behind_master的精度误差
[MAF预定义ChatClient中间件-03]CachingChatClient——利用缓存省钱省时间
AI的至暗历史:从万众期待到被政府撤资,AI的两次死亡徘徊
Agent OS :五种驯服不确定性的范式
PortSwigger SQL注入LAB11
数据库即时编译JIT
[Begin]AI Learn Data Day 0
深度学习进阶(二十七)现代 LLM 的核心架构设计其二:SwiGLU