【问题标题】:encode data to send to a websocket server编码数据以发送到 websocket 服务器
【发布时间】:2014-06-22 19:56:17
【问题描述】:

在尝试连接到 websocket 服务器并向其发送信息后,我遇到了编码问题。 我有一个字符串和这个字符串的编码(十六进制)版本。假设我的字符串是 'getpremium' 我如何将该字符串转换为这些十六进制值的数组?

[0x81, 0x8c, 0x86, 0x78, 0xe3, 0xc6, 0xe1, 0x1d,
0x97, 0xb6, 0xf4, 0x1d, 0x8e, 0xaf, 0xf3, 0x15,
0xee, 0xcc]

我可以将这些值解码回原始字符串,但我不知道如何将它们编码为这些十六进制值。基本上,我如何对该字符串“getpremium”进行编码以获取这些编码值以将它们发送到此 websocket 服务器。任何使用 python 或 node.js 的方法都适用。

javascript解码方式:

var _ = require("underscore");
function decode(data){
        if (typeof data === 'string') {
                data = _.map(data, function(chr){ return chr.charCodeAt(0); });
        }
        var datalength = data[1] & 127;
        var indexFirstMask = 2;
        if (datalength == 126) {
                indexFirstMask = 4;
        } else if (datalength == 127) {
                indexFirstMask = 10;
        }
        var masks = data.slice(indexFirstMask,indexFirstMask + 4);
        var i = indexFirstMask + 4;
        var index = 0;
        var output = "";
        while (i < data.length) {
                x = data[i++] ^ masks[index++ % 4];
                output += String.fromCharCode(x);
        }
        return output;
}

【问题讨论】:

    标签: python node.js sockets websocket


    【解决方案1】:

    试试这个:

    import os
    
    def encode(rawBytes):
        data = [ord(i) for i in rawBytes]
        length = len(rawBytes) + 128
        Bytes = [0x81, length]
        index = 2
        masks = os.urandom(4)
        for i in range(len(masks)):
               Bytes.insert(i + index, masks[i])        
        for i in range(len(data)):
            data[i] ^= masks[i % 4]
            Bytes.insert(i + index + 4, data[i])
        return [hex(i) for i in Bytes]
    

    【讨论】:

      猜你喜欢
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      相关资源
      最近更新 更多