• java实现websocket握手协议


    1. String str = new String(data, CHARSET);
    2. String[] arr = str.split("\r\n");
    3. String[] temp = arr[0].split(" ");
    4. Map map = this.toMap(arr);
    5. String base64 = generateWebSocketAccept((String)map.get("Sec-WebSocket-Key"));
    6. StringBuffer sb = new StringBuffer(200);
    7. sb.append(temp[2]).append(" 101 Switching Protocols\r\n");
    8. sb.append("Upgrade: websocket\r\n");
    9. sb.append("Connection: Upgrade\r\n");
    10. sb.append("Sec-WebSocket-Accept: ").append(base64).append("\r\n\r\n");

    其中最重要的是最后几个换行不要丢,将字符串转成byte[]写给客户端即可

    1. public static String generateWebSocketAccept(String webSocketKey) {
    2. System.out.println(webSocketKey);
    3. try {
    4. String acc = webSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    5. MessageDigest sh1 = MessageDigest.getInstance("SHA1");
    6. sh1.update(acc.getBytes(CHARSET), 0, acc.length());
    7. return Base64.getEncoder().encodeToString(sh1.digest());
    8. } catch (NoSuchAlgorithmException e) {
    9. throw new RuntimeException("SHA-1 algorithm not found", e);
    10. }
    11. }

    收到的掩码转换

    1. int i, j;
    2. for(i=0, j=0; i
    3. data[j] = (byte) (data[i] ^ masks[j % 4]);
    4. }

    下面是服务器向客户端发送消息

    1. public byte[] doSend(String mess) throws IOException{
    2. byte[] rawData = mess.getBytes();
    3. int frameCount = 0;
    4. byte[] frame = new byte[10];
    5. frame[0] = (byte) 129;
    6. if(rawData.length <= 125){
    7. frame[1] = (byte) rawData.length;
    8. frameCount = 2;
    9. }else if(rawData.length >= 126 && rawData.length <= 65535){
    10. frame[1] = (byte) 126;
    11. int len = rawData.length;
    12. frame[2] = (byte)((len >> 8 ) & (byte)255);
    13. frame[3] = (byte)(len & (byte)255);
    14. frameCount = 4;
    15. }else{
    16. frame[1] = (byte) 127;
    17. int len = rawData.length;
    18. frame[2] = (byte)((len >> 56 ) & (byte)255);
    19. frame[3] = (byte)((len >> 48 ) & (byte)255);
    20. frame[4] = (byte)((len >> 40 ) & (byte)255);
    21. frame[5] = (byte)((len >> 32 ) & (byte)255);
    22. frame[6] = (byte)((len >> 24 ) & (byte)255);
    23. frame[7] = (byte)((len >> 16 ) & (byte)255);
    24. frame[8] = (byte)((len >> 8 ) & (byte)255);
    25. frame[9] = (byte)(len & (byte)255);
    26. frameCount = 10;
    27. }
    28. int bLength = frameCount + rawData.length;
    29. byte[] reply = new byte[bLength];
    30. int bLim = 0;
    31. for(int i=0; i
    32. reply[bLim] = frame[i];
    33. bLim++;
    34. }
    35. for(int i=0; i
    36. reply[bLim] = rawData[i];
    37. bLim++;
    38. }
    39. return reply;
    40. }

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