java生成 Sec-WebSocket-Accept的密钥

   public static String generateWebSocketAccept(String webSocketKey) {
        String keyString = webSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            byte[] hash = messageDigest.digest(keyString.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeToString(hash, Base64.NO_WRAP);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 algorithm not found", e);
        }
    }
参数webSocketKey是客户端请求过来的Sec-WebSocket-Key这个头。

具体的请求和响应的例子如下

Handshake Details
    Request URL: http://127.0.0.1:8080/home/user.websocket
    Request Method: GET
    Status Code: 101 Switching Protocols
    Request Headers
    Sec-WebSocket-Version: 13
    Sec-WebSocket-Key: VKK/4ExbQre/XX9rB4yDlg==
    Connection: Upgrade
    Upgrade: websocket
    Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
    Host: 127.0.0.1:8080
    
Response Headers
    Connection: Upgrade
    Upgrade: WebSocket
    Sec-WebSocket-Accept: iJKFTUb56s8x38R5xL1Bp/roB40=

你可能感兴趣的:(java,websocket,开发语言)