如何在命令行上将数据发送到nodeJS websocket?

时间:2018-03-23 19:59:16

标签: node.js sockets command-line websocket

我有一个节点JS Web套接字服务器,设置如此

// Miner Proxy Srv
var srv = new WebSocket.Server({
    server: web,
    path: "/proxy",
    maxPayload: 1024
});
srv.on('connection', (ws) => {
    var conn = {
        uid: null,
        pid: crypto.randomBytes(12).toString("hex"),
        workerId: null,
        found: 0,
        accepted: 0,
        ws: ws,
        pl: new net.Socket(),
    }

我的问题是如何连接到Web套接字并向其发送数据?我下载了“wscat”并尝试了下面的

wscat -c ws://localhost:8000/proxy -p 13 -H "Host:localhost.localdomain.com" -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" -H "Sec-WebSocket-Version: 13" '{"type":"auth","params":{"site_key":{"IF_EXCLUSIVE_TAB":"ifExclusiveTab","FORCE_EXCLUSIVE_TAB":"forceExclusiveTab","FORCE_MULTI_TAB":"forceMultiTab","CONFIG":{"LIB_URL":"https://localhost.localdomain.com/lib/","WEBSOCKET_SHARDS":[["wss://localhost.localdomain.com/proxy"]]},"CRYPTONIGHT_WORKER_BLOB":"blob:https://localhost.localdomain.com/54f39ac6-5c2a-4ff1-8052-c4e0e508034c"},"type":"anonymous","user":null,"goal":0}}'

但我收到了错误

error: Error: invalid server key

当我运行上述内容时。

1 个答案:

答案 0 :(得分:0)

默认情况下,

wscat会为请求生成有效的标头Sec-WebSocket-Key,因此只需从命令行中删除-H "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ=="即可。我已经调试并发现下面的标题已经创建,即使我没有使用wscat通过命令行传递它们。

srv.on('connection', (ws,req) => {
    console.log(req.headers);
     /*
     //headers present without passing arguments to wscat
     { 'sec-websocket-version': '13',
       'sec-websocket-key': 's3pPLMBiTxaQ9kYGzzhZRbK+xOo=',
        connection: 'Upgrade',
        upgrade: 'websocket',

        .....
     */
     ......

所以使用以下命令:

wscat -c ws://localhost:8000/proxy -p 13 -H "Host:localhost.localdomain.com" -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Sec-WebSocket-Version: 13" '{"type":"auth","params":{"site_key":{"IF_EXCLUSIVE_TAB":"ifExclusiveTab","FORCE_EXCLUSIVE_TAB":"forceExclusiveTab","FORCE_MULTI_TAB":"forceMultiTab","CONFIG":{"LIB_URL":"https://localhost.localdomain.com/lib/","WEBSOCKET_SHARDS":[["wss://localhost.localdomain.com/proxy"]]},"CRYPTONIGHT_WORKER_BLOB":"blob:https://localhost.localdomain.com/54f39ac6-5c2a-4ff1-8052-c4e0e508034c"},"type":"anonymous","user":null,"goal":0}}'

我希望它有所帮助。