How to send string over UDP using Javascript on Ch

2019-08-01 09:58发布

问题:

i am writing a chrome app, and i want to send some strings over UDP to some server. i'm new to javascript and i'm kinda stuck. this is a snippet of the code:

var wholeString = "what is the meaning of life";            

chrome.sockets.udp.create({}, function (socketInfo) {
    // The socket is created, now we can send some data
    var socketId = socketInfo['socketId'];
    var arrayBuffer = stringToArrayBuffer("hello");
    chrome.sockets.udp.bind(socketId, "127.0.0.1", 0, function (result) {
        chrome.sockets.udp.send(socketId, stringToArrayBuffer(wholeString), "127.0.0.1", 3050, function (sendInfo) {
            console.log("sent " + sendInfo.bytesSent);
            if (sendInfo.resultCode < 0) {
                console.log("Error listening: " + chrome.runtime.lastError.message);
            }
        });
    });
});

the problem lies when i try to send(), and the argument stringToArrayBuffer(wholeString) is problematic. the stringToArrayBuffer() is here:

function stringToArrayBuffer(string) {
    var arrayBuffer = new ArrayBuffer(string.length * 2);
    var buffer = new Uint8Array(arrayBuffer);
    for (var i = 0, stringLength = string.length; i < stringLength; i++) {
        buffer = string.charCodeAt(i);
    }
    return buffer;
}

The error message i get is:

Error in response to sockets.udp.bind: Error: Invocation of form sockets.udp.send(integer, integer, string, integer, function) doesn't match definition sockets.udp.send(integer socketId, binary data, string address, integer port, function callback)
    at Object.callback (chrome-extension://pmkjeflkfhfekliappbhemngaejmnbec/helper.js:45:24)
    at Object.callback (chrome-extension://pmkjeflkfhfekliappbhemngaejmnbec/helper.js:42:23)

i thought the function will change my string to a byte array? whats wrong??

回答1:

There's a tiny mistake in your stringToArrayBuffer function.

function stringToArrayBuffer(string) {
    var arrayBuffer = new ArrayBuffer(string.length * 2);
    var buffer = new Uint8Array(arrayBuffer);
    for (var i = 0, stringLength = string.length; i < stringLength; i++) {
        buffer[i] = string.charCodeAt(i);
        // Was: buffer = string.charCodeAt(i);
    }
    return buffer;
}

So you were overwriting the binary array with just one integer value.

I am not sure it's the only problem though. Why are you using Uint8 instead of Uint16? See this guide linked from Chrome docs.