java实现websocket握手协议

文章介绍了使用Java实现WebSocket服务器的过程,包括生成WebSocketAccept密钥、接收和处理掩码以及构建和发送数据帧,重点在于加密算法和数据包格式的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String str = new String(data, CHARSET);
        String[] arr = str.split("\r\n");
        String[] temp = arr[0].split(" ");
        Map<String, String> 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.length; i++, j++) {
            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<frameCount;i++){
            reply[bLim] = frame[i];
            bLim++;
        }
        for(int i=0; i<rawData.length;i++){
            reply[bLim] = rawData[i];
            bLim++;
        }

        return reply;

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值