Trying to use TCP sockets using chrome.socket
API on Chrome Version 25.0.1364.5 dev.
Looking at the documentation for the chrome.socket.read
there doesn't seem to be a way to get a notification when new data is available to be read.
There is some sample code for a TCP server which polls the read command every 500ms but I think this would not be efficient / accurate
// Start polling for reads.
setInterval(this._periodicallyRead.bind(this, socketId), 500);
What's more confusing is that in the 'Network Communications' Documentation under section 'Receiving data', it is stated that a special handler can be passed as an onEvent
option in chrome.socket.create
The parameter is an object with one value 'onEvent' that is a function reference to the method that will be called when data is available on the port.
This onEvent parameter would be used like this
chrome.socket.create(
'udp', '127.0.0.1', 1337,
{ onEvent: handleDataEvent }, // <-- call this when new data is available
createHandler
)
But this appears to apply only for UDP connections as I get the following error when I try to use it
Error: Invocation of form
socket.create(string, string, integer, object, function)
doesn't match definition
socket.create(string type, optional object options, function callback)
at Object.normalizeArgumentsAndValidate (schemaUtils:119:11)
at Object.<anonymous> (schema_generated_bindings:301:32)
at chrome-extension://obljaojhdffbpcdfbeoiejegaodfoonp/background.js:11:15
at chrome.Event.dispatchToListener (event_bindings:387:21)
at chrome.Event.dispatch_ (event_bindings:373:27)
at dispatchArgs (event_bindings:249:22)
at Object.app.runtime.onLaunched (app.runtime:116:7)
at Object.chromeHidden.Event.dispatchEvent (event_bindings:255:35)
So the question is, can something like this be achieved with TCP Connections ? Instead of having to poll the read
method every x milliseconds ?
Update
This is a workaround I am using until better documentation / event support exists.
function onReadHandler(readInfo) {
// do things with data
// ....
// re register handler with callback itself
chrome.socket.read(socketId,null,onReadHandler);
}
chrome.socket.read(socketId,null,onReadHandler);
onEvent:
did not work fortcp
sockets?onEvent
in the API docs. Also, the API talks aboutcallback
parameters, but none of the socket functions are specified to accept callbacks. The docs look to be a bit of mess right now.