I'm writing a little javascript application trying to use the Chrome sockets API. The code doesn't seem terribly relevant, though, because I'm getting an error on the very first line:
var socket = chrome.sockets.udp;
On that line, I get an Uncaught TypeError: cannot read property 'udp' of undefined. So chrome.sockets isn't being defined for some reason, but for the life of me I can't seem to figure out what. Is there something I need to include or import to use Chrome APIs? The API doc hasn't been helpful in that regard.
EDIT: background.js file:
var socket = chrome.sockets.udp;
var PORT = 5005;
var HOST = '127.0.0.1';
var sockInfo;
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('window.html', {
'bounds': {
'width': 400,
'height': 500
}
});
init();
});
function init(){
socket.create({}, function(_sockInfo){
sockInfo = _sockInfo;
socket.bind(sockInfo.socketId, HOST, PORT, function(result){
if(result < 0){
throw "Bind failed"
}
console.log("Socket created and bound.");
socket.onReceive.addListener(function(info){
console.log('Received packet from ' + info.remoteAddress +
' : ' + info.remotePort + ', length ' + info.data.length);
});
});
});
}
Related
Add chrome cast according to the tutorial.
After adding the Chromecast button, I click it, select an available device from the network, and it is connected. The status "Streaming" is visible in the browser, in fact nothing happens, except for the following error in the console:
TypeError: Cannot read property 'loadMedia' of null
Code:
cast.framework.CastContext.getInstance().setOptions({
receiverApplicationId: '111111',
autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED
});
var currentMediaURL =
'https://.....';
var contentType = 'mp4';
var mediaInfo = new chrome.cast.media.MediaInfo(currentMediaURL,contentType);
var request = new chrome.cast.media.LoadRequest(mediaInfo);
console.log('Below variable -mediaInfo ');
console.log(mediaInfo);
console.log('Below variable -request ');
console.log(request);
var castSession = cast.framework.CastContext.getInstance().getCurrentSession();
console.log('Below variable -castSession ');
console.log(castSession);
castSession.loadMedia(request).then(
function () {
console.log('Load succeed');
},
function (errorCode) {
console.log('Error code: ' + errorCode);
});
Code testing:
As I understand it, for some reason, the link to the stream is not sent.
There is an interesting question, why does the link to the stream go to the variable contentid although there is a variablecontentUrl?
I'm writing a simple flask application in python using flask-socket. On the console I'm facing:
"[Error] ReferenceError: Can't find variable: socket"
and
"ReferenceError: Can't find variable: require"
I'm attaching snippets of codes that might be relevant. I'd appreciate any hints.
document.addEventListener('DOMContentLoaded', () => {
//connect to websocket
var io = require('/Users/august/Desktop/project2/venv/lib/python3.7/site-packages/socketio');
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
//when connected, configure buttons
socket.on('connect', () => {
// button should emit 'send message' event
document.querySelector("#submit-message").onclick = () => {
const message = document.querySelector("#message").value;
socket.emit('send message', {"message": message});
};
});
});
I am trying to integrate Coinbase with Node Js, but I am unable to execute the code given on the tutorial page. My code is
`var coinbase = require('coinbase');
var client = new coinbase.Client({'apiKey': mykey, 'apiSecret': mysecret});
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log('my bal: ' + acct.balance.amount + ' for ' + acct.name);
});
});`
I get t the following error:
accounts.forEach(account => {
^
typeError: Cannot read property 'forEach' of null
Looking forward to your answer! Thanks!
The error is clear: accounts is equal to null. You should check what's in err before working with accounts
hello you can use like this
client.getAccounts({}, function(err, accounts) {
accounts.forEach(function(acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id );
});
});
You could try with a different API keys and check if the keys are enabled.
var Client = require('coinbase').Client;
var client = new Client({
'apiKey': 'API KEY',
'apiSecret': 'API SECRET'
});
client.getAccounts({}, function (err, accounts) {
accounts.data.forEach(function (acct) {
console.log(acct.name + ': ' + acct.balance.amount + ' ' + acct.id);
});
});
Also accounts returns a lot of information but we are looking at the data block. Please refer the Coinbase API v2 documentation for complete sample response of the getAccounts() call - https://developers.coinbase.com/api/v2?javascript#account-resource
Let us know if this works. Good luck!
I need some help about my node.js+socket.io implementation.
This service expose a server that connects to an ActiveMQ broker over the STOMP protocol, using the stomp-js node.js module to receive events; that then are displayed in a web front end through websockets using socket.io.
So, everything was fine until I started use the Filters feature of ActiveMQ, but this was not the failure point because of my and my team researching, we found the way to ensure the implementation was fine, the problem comes with the connections: So here's the thing, I receive the filters to subscribe, I successfully subscribe to but when I receive a new set of filters is when comes the duplicated, triplicated and more and more messages depending the number of times that I subscribe-unsubscribe to.
So making some debug, I cannot see what's the problem but I'm almost sure that is some bad implementation of the callbacks or the program flow, I'll attach my code to read your comments about it.
Thanks a lot!
var sys = require('util');
var stomp = require('stomp');
var io = require('socket.io').listen(3000);
var socket = io.sockets.on('connection', function (socket) {
var stomp_args = {
port: 61616,
host: 'IP.ADDRESS',
debug: true,
};
var headers;
var client = new stomp.Stomp(stomp_args);
var setFilters = false;
socket.on('filtros', function (message) {
console.log('DEBUG: Getting filters');
if(setFilters){
client.unsubscribe(headers);
}
else{
client.connect();
}
var selector = '';
headers = '';
for(var attributename in message){
console.log(attributename+" : " + message[attributename]);
if(message[attributename] != ''){
selector += ' ' + attributename + '=\'' + message[attributename] + '\' AND ';
}
}
selector = selector.substring(0, selector.length - 4)
console.log('DEBUG: Selector String: ' + selector);
headers = {
destination: '/topic/virtualtopic',
ack: 'client',
selector: selector
};
if(setFilters)
client.subscribe(headers);
client.on('connected', function() {
client.subscribe(headers);
console.log('DEBUG: Client Connected');
setFilters = true;
});
});
var bufferMessage;
client.on('message', function(message) {
console.log("Got message: " + message.headers['message-id']);
var jsonMessage = JSON.parse(message.body);
if(bufferMessage === jsonMessage){
console.log('DEBUG: recibo un mensaje repetido');
return 0;
}
else{
console.log('DEBUG: Cool');
socket.emit('eventoCajero', jsonMessage);
}
client.ack(message.headers['message-id']);
bufferMessage = jsonMessage;
});
socket.on('disconnect', function(){
console.log('DEBUG: Client disconnected');
if(setFilters){
console.log('DEBUG: Consumer disconnected');
client.disconnect();
}
});
client.on('error', function(error_frame) {
console.log(error_frame.body);
});
});
Looking in the Socket.IO documentation, I've found that this is a known issue (I think critical known issue) and they have not fixed it yet. So, to correct this is necessary to reconnect to the socket in the client side to avoid duplicate messages, using:
socket.socket.reconnect();
function to force reconnection explicitly.
I'm trying to get UDP sockets working for a packaged app using Chrome Canary (currently version 25). I am pretty confused by the fact the UDP example here conflicts with the reference documentation here.
The official example uses this line:
chrome.socket.create('udp', '127.0.0.1', 1337, { onEvent: handleDataEvent }, ...
In Canary using this line results in the error:
Uncaught Error: Invocation of form socket.create(string, string,
integer, object, function) doesn't match definition
socket.create(string type, optional object options, function callback)
Not surprising since that matches the documented form of the function. (I guess the example is out of date?) OK, so I try this...
chrome.socket.create('udp', { onEvent: handleDataEvent }, ...
Canary complains:
Uncaught Error: Invalid value for argument 2. Property 'onEvent':
Unexpected property.
Now I'm confused, especially since this parameter is undocumented in the reference. So I just go with this:
chrome.socket.create('udp', {}, ...
Now it creates OK, but the following call to connect...
chrome.socket.connect(socketId, function(result) ...
...fails with this:
Uncaught Error: Invocation of form socket.connect(integer, function)
doesn't match definition socket.connect(integer socketId, string
hostname, integer port, function callback)
...which is not surprising, since now my code doesn't mention a host or port anywhere, so I guess it needs to be in connect. So I change it to the form:
chrome.socket.connect(socketId, address, port, function (result) ...
At last I can connect and write to the socket OK. But this doesn't cover reading.
Can someone show me a working example based on UDP that can send & receive, so I can work from that?
How do I receive data since the example's onEvent handler does not work? How do I ensure I receive any data on-demand as soon as it arrives without blocking?
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);
});
});