- 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;
-
- }
-
相关阅读:
uniapp开发小程序-工作笔记
Geotools实现shape文件的写入
代码整洁之道
回归分析
什么是nginx到底怎么配置,什么是网关到底怎么配置?
【架构设计】作为架构师你应该掌握的画图技术
经颅直流电刺激对大脑网络的调制
JUC - 线程基础
安阳旅游地图规划(未完成)
【无标题】
-
原文地址:https://blog.csdn.net/zml_moxueli/article/details/132880594