- 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;
-
- }
-
相关阅读:
上海亚商投顾:沪指震荡调整跌 减肥药、华为概念股持续活跃
【迷宫问题】通过DFS和BFS两种方式求解迷宫问题
Python刷题系列(9)_Pandas_Series
063:vue+openlayers绘制自由线段、自由多边形(代码示例)
【云原生 | Kubernetes 系列】---Skywalking 告警
【MacOs系统-M2安装2022新版AWVS渗透工具】-保姆级安装教程
【秋招基础】【2】笔试笔记
fio performance test
linux下定位内存泄漏 /proc/pid/status 解释
【深度学习】基于YOLOV5模型的图像识别-目标检测的性能指标详解与计算方法
-
原文地址:https://blog.csdn.net/zml_moxueli/article/details/132880594