1

我正在尝试使用 Chrome Canary(当前版本 25)让 UDP 套接字适用于打包的应用程序。我对此处的UDP 示例与此处的参考文档冲突这一事实感到非常困惑。

官方示例使用这一行:

chrome.socket.create('udp', '127.0.0.1', 1337, { onEvent: handleDataEvent }, ...

在 Canary 中使用此行会导致错误:

未捕获的错误:调用表单 socket.create(string, string, integer, object, function) 与定义 socket.create(string type, optional object options, function callback) 不匹配

这并不奇怪,因为这与函数的文档形式相匹配。(我猜这个例子已经过时了?)好的,所以我试试这个......

chrome.socket.create('udp', { onEvent: handleDataEvent }, ...

金丝雀抱怨:

未捕获的错误:参数 2 的值无效。属性“onEvent”:意外属性。

现在我很困惑,特别是因为这个参数在参考文献中没有记录。所以我只是这样做:

chrome.socket.create('udp', {}, ...

现在它创建好了,但是下面的调用connect...

chrome.socket.connect(socketId, function(result) ...

...失败了:

未捕获的错误:调用表单 socket.connect(integer, function) 与定义 socket.connect(integer socketId, string hostname, integer port, function callback) 不匹配

...这并不奇怪,因为现在我的代码没有在任何地方提到主机或端口,所以我想它需要在connect. 所以我将其更改为以下形式:

chrome.socket.connect(socketId, address, port, function (result) ...

最后我可以连接并写入套接字了。但这不包括阅读。

  • 有人可以向我展示一个可以发送和接收的基于 UDP 的工作示例,以便我可以使用它吗?
  • 由于示例的 onEvent 处理程序不起作用,我如何接收数据?我如何确保在数据到达后立即按需接收数据而不会阻塞?
4

1 回答 1

8

The Network Communications doc is not up-to-date. See the latest API doc: https://developer.chrome.com/trunk/apps/socket.html. But the doc doesn't state everything clearly. I looked into Chromium source code and found some useful comments here: https://code.google.com/searchframe#OAMlx_jo-ck/src/net/udp/udp_socket.h&q=file:(%5E%7C/)net/udp/udp_socket%5C.h$&exact_package=chromium

// Client form:
// In this case, we're connecting to a specific server, so the client will
// usually use:
//       Connect(address)    // Connect to a UDP server
//       Read/Write          // Reads/Writes all go to a single destination
//
// Server form:
// In this case, we want to read/write to many clients which are connecting
// to this server.  First the server 'binds' to an addres, then we read from
// clients and write responses to them.
// Example:
//       Bind(address/port)  // Binds to port for reading from clients
//       RecvFrom/SendTo     // Each read can come from a different client
//                           // Writes need to be directed to a specific
//                           // address.

For the server UDP socket, call chrome.socket.bind and chrome.socket.recvFrom/chrome.socket.sendTo to interact with clients. For the client UDP socket, call chrome.socket.connect and chrome.socket.read/chrome.socket.write to interact with the server.

Here's an example:

var serverSocket;
var clientSocket;

// From https://developer.chrome.com/trunk/apps/app_hardware.html
var str2ab=function(str) {
  var buf=new ArrayBuffer(str.length);
  var bufView=new Uint8Array(buf);
  for (var i=0; i<str.length; i++) {
    bufView[i]=str.charCodeAt(i);
  }
  return buf;
}

// From https://developer.chrome.com/trunk/apps/app_hardware.html
var ab2str=function(buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
};

// Server
chrome.socket.create('udp', null, function(createInfo){
    serverSocket = createInfo.socketId;

    chrome.socket.bind(serverSocket, '127.0.0.1', 1345, function(result){
        console.log('chrome.socket.bind: result = ' + result.toString());
    });

    function read()
    {
        chrome.socket.recvFrom(serverSocket, 1024, function(recvFromInfo){
            console.log('Server: recvFromInfo: ', recvFromInfo, 'Message: ', 
                ab2str(recvFromInfo.data));
            if(recvFromInfo.resultCode >= 0)
            {
                chrome.socket.sendTo(serverSocket, 
                    str2ab('Received message from client ' + recvFromInfo.address + 
                    ':' + recvFromInfo.port.toString() + ': ' + 
                    ab2str(recvFromInfo.data)), 
                    recvFromInfo.address, recvFromInfo.port, function(){});
                read();
            }
            else
                console.error('Server read error!');
        });
    }

    read();
});

// A client
chrome.socket.create('udp', null, function(createInfo){
    clientSocket = createInfo.socketId;

    chrome.socket.connect(clientSocket, '127.0.0.1', 1345, function(result){
        console.log('chrome.socket.connect: result = ' + result.toString());
    });

    chrome.socket.write(clientSocket, str2ab('Hello server!'), function(writeInfo){
        console.log('writeInfo: ' + writeInfo.bytesWritten + 
            'byte(s) written.');
    });

    chrome.socket.read(clientSocket, 1024, function(readInfo){
        console.log('Client: received response: ' + ab2str(readInfo.data), readInfo);
    });
});
于 2012-12-04T04:57:02.667 回答