我写一个Chrome应用,我想通过UDP发送一些字符串到一些服务器。 我是新来的JavaScript和我有点卡住。 这是代码的一个片段:
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);
}
});
});
});
问题的关键在于,当我尝试发送(),和参数stringToArrayBuffer(wholeString)
是有问题的。 在stringToArrayBuffer()
是在这里:
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;
}
该错误消息我得到的是:
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)
我认为该函数将我的字符串更改为一个字节数组? 怎么了??