我尝试将以下代码作为解压缩的chrome扩展程序运行,并在我的控制台中获得以下输出:
clicked
sent undefined
Error listening: net::ERR_SOCKET_NOT_CONNECTED
我也在使用一个单独的软件在端口11111上创建一个UDP服务器,它什么都没有收到。
的manifest.json
{
"name": "UDP Test",
"description": "Testing UDP connection.",
"version": "0.1",
"app": {
"background": {
"scripts": ["background.js"]
}
},
"minimum_chrome_version": "33",
"sockets": {
"udp": {
"send": "*"
}
}
}
background.js
// On app launch
chrome.app.runtime.onLaunched.addListener(function() {
// Create window
chrome.app.window.create('window.html', {
'bounds': {
'width': 400,
'height': 500
}
});
});
window.html
<html>
<head>
<button id="test">Run</button>
<script src="network.js"></script>
</head>
<body>
</body>
</html>
network.js
test.addEventListener('click', function() {
console.log("clicked");
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.send(socketId, stringToArrayBuffer("hello"), "127.0.0.1", 11111, function(sendInfo) {
console.log("sent " + sendInfo.bytesSent);
if (sendInfo.resultCode < 0) {
console.log("Error listening: " + chrome.runtime.lastError.message);
}
});
});
});
function stringToArrayBuffer(string) {
var buffer = new ArrayBuffer(string.length * 2);
var bufferView = new Uint16Array(buffer);
for (var i = 0, stringLength = string.length; i < stringLength; i++) {
bufferView = string.charCodeAt(i);
}
return buffer;
}
为什么会发生这种情况?我找到了几个chrome udp的例子,但他们都使用了实验性的API而不是这个。
答案 0 :(得分:4)
你缺少bind()。文档说&#34;在调用[send]方法之前,套接字必须绑定到本地端口。&#34;