I am using below javascript code to connect to autobahn server. All these times I was using static ip but now the ip is going to be dynamic. How can I pass dynamic server ip and get autobahn connected dynamically?
var connection = new autobahn.Connection({url: 'ws://<ip>:8080/ws', realm: 'realm1'});
var openSession = null;
connection.onopen = function (session) {
openSession = session;
window.JSInterface.isConnected(true);
};
connection.onClose = function(reason, details) {
openSession = null;
window.JSInterface.isConnected(false);
}
There are to options:
Take a domain name instead of an IP e.g ws://autobahn.de:8080/ws
You have a service where you can fetch the ip an then pass it with a variable for example:
var connectionIP = 8.8.8.8;
var connection = new autobahn.Connection({url:'ws://'+connectionIP+':8080/ws', realm: 'realm1'});
Related
I'm trying to implement Google Analytics Graphs via their Javascript API, as the example on their site link.
But I keep getting "401 Invalid Credentials" each time I try to execute gapi.analytics.googleCharts.DataChart
I'm getting the access token server side (C#) using the following code with data from the JSON generated for the Service Account
var cred = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(clientId)
{
Scopes = new[] { AnalyticsReportingService.Scope.AnalyticsReadonly },
User = clientEmail,
ProjectId = "projectID"
}.FromPrivateKey(privateKey));
var token = cred.GetAccessTokenForRequestAsync(authURI);
token.Wait();
var result = token.Result;
return result;
or (using the full json string, see Note too)
GoogleCredential cred;
var gCred = GoogleCredential.FromJson(json).UnderlyingCredential as
ServiceAccountCredential;
var token = gCred.GetAccessTokenForRequestAsync("https://accounts.google.com/o/oauth2/auth");
return token.Result;
While on the client side
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': '{{ ACCESS_TOKEN_FROM_SERVICE_ACCOUNT }}'
}
});
goes through and using gapi.analytics.auth.isAuthorized() returns true using any of the server side functions but it fails when trying to call
var dataChart1 = new gapi.analytics.googleCharts.DataChart(queryJson);
dataChart1.execute();
returns 401 "Invalid Credentials", the server side query returns values just fine so I think the user permissions is not the issue
NOTE: Using the same code as the second one (generating the credential using the json string without casting as a ServiceAccountCredential) I can get data from the API server side
cred = gCred.CreateScoped(scopes);
using (var reportingService = new AnalyticsReportingService(new BaseClientService.Initializer
{
HttpClientInitializer = cred
}))
...
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute(); //This returns a response object with all the data I need
If anyone has the same issue:
You need to use GoogleCredential.GetApplicationDefault() to create the Credential object, in the case of Analytics you should get something like this
var credential = GoogleCredential.GetApplicationDefault().CreateScoped(AnalyticsReportingService.Scope.AnalyticsReadonly);
This will get the json file from the Environment Variables on Windows, so you need to set GOOGLE_APPLICATION_CREDENTIALS with the path to the json as a System Variable.
Initialize the service and set the service variable
using (var reportingService = new AnalyticsReportingService(new BaseClientService.Initializer { HttpClientInitializer = credential }))
{
var serviceCredential = cred.UnderlyingCredential as ServiceAccountCredential;
}
I am trying to capture client ipaddress for traffic visiting my localhost:8080. I am using the following modules and the node.js application looks like this
var connect = require('connect');
var http = require('http');
var net = require('net');
var express = require('express');
var app = express();
var app = connect();
// require request-ip and register it as middleware
var requestIp = require('request-ip');
// you can override which attirbute the ip will be set on by
// passing in an options object with an attributeName
app.use(requestIp.mw({ attributeName : 'myCustomAttributeName' }))
// respond to all requests
app.use(function(req, res) {
// use our custom attributeName that we registered in the middleware
var ip = req.myCustomAttributeName;
console.log(ip);
fs.appendFile('iplist.csv', ip, 'utf8', function (err) {
if (err) {
console.log('Some error occured - file either not saved or corrupted file saved');
} else{
console.log('It\'s saved!');
}
});
// https://nodejs.org/api/net.html#net_net_isip_input
// var ipType = net.isIP(ip); // returns 0 for invalid, 4 for IPv4, and 6 for IPv6
// res.end('IP address is ' + ip + ' and is of type IPv' + ipType + '\n');
});
//create node.js http server and listen on port
app.listen(8080);
Is there any way I can listen to the already existing server without creating my own, hence avoiding the conflict of two servers fighting for the same port. I am new to node.js. Any help will be great. Thank you!
Today I hit the wall while writing TCP server in node js ...
I need to make TCP server for windows and android app: Using just nodejs net module ...
there is app class in with is called server class that creates several Client instances. one on each connection ...
And in each of these client instances, I need a global var that is visible in "current" instance of client...and recursively in all other instances, that's been invoked in client class instance.
I need that global var for holding session content like vars, objects, and crypt keys ... for all instances called in Client class instance and so one... without passing values to every new instane ...
//app.js
var Server = require("./core/server/Server");
console.log('hi!');
console.dir("there is nothing to look at at the momment");
global.DEBUG = true;
global.NEW_GUID = require('uuid/v4');
var server = new Server()
server.start();
//server.js
const net = require('net');
const Client = require("./Client");
class Server{
constructor (port, address) {
this.port = port || 4484;
this.address = address || '127.0.0.1';
this.clients = [];
}
start(callback) {
let server = this;
server.connection = net.createServer((socket) => {
socket.setEncoding("UTF8");
let client = new Client(socket);
server.clients.push(client);
socket.on('error',(e)=>{ console.dir(e); })
socket.on('end', () => {});
});
this.connection.listen(this.port, this.address);
}
}
module.exports = Server;
//Client.js
//req some components
GLOBAL_VAR = {
login :"a",
sess_crypt: "encryption instance setuped in client",
socket:seocket
}
class Client {
constructor(socket) {
//some this vars }
async GetLogin() {
}
async GetData(d) {
}
StartDialog() {
}
serverHandler(){
console.log(`${this.name} connected.`);
//client.GetLogin();
this.socket.write("WELCOME\r\n")
this.socket.on("data", (d) => {
var ed = Buffer.from(d);
console.dir(ed.toString("UTF8"));
this.GetData(ed).then((r)=>{
if (r.cmd == "LOGIN") {
this.sth = new sth();
this.sth.sth(); // inside this you can have multiple calls of sth and i can't pass any value by parameter because of rest "old" js code what was running on RHINo Java server that i can't modifi to much
}
})
})
}
}
module.exports = Client;
///sth.js
//req some components
class sth extends other_staf{
constructor() {
this.login = GLOBAL_VAR.login
}
oninit(){
// do staf start next instance of sth()
}
sth(){
GLOBAL_VAR.socket.write(GLOBAL_VAR.sess_crypt("some request\r\n"))
this.oninit();
}
}
module.exports = sth;
You don't need global variables. You can try to do something like this, define data in Client so like so
var client = new Client();
client.data.name = "client 1";
or better pass it to contructor:
var client = new Client({name: "client 1"});
and in constructor use
function Client(options) {
this.data = options;
// ...
}
and pass client object to instances:
var instance = new instance(client);
and access:
instance.client.data.name;
if that box you have in proved image is the inside of the object then you can use this instead of instance and client.
i want to send a websocket, using express-ws out from a different controller, not by route and I have the following code in the server.js:
var SocketController = require('./routes/ws.routes');
var app = express();
var server = require('http').createServer(app);
var expressWs = require('express-ws')(app);
app.ws('/', SocketController.socketFunction);
the SocketController looks like that:
exports.socketFunction = function (ws, req) {
ws.on('message', function(msg) {
console.log(msg);
ws.send("hello");
});
}
Is it possible to call the
ws.send()
event from another controller? How do i get the "ws" object?
thanks!
You will have to store your sockets in memory. To access stored sockets from different modules, you can store references for these sockets in a separate module.
For example, you can create a module socketCollection that stores all the active sockets.
socketCollection.js:
exports.socketCollection = [];
You can import this module where you define your web socket server:
var socketCollection = require('./socketCollection');
var SocketController = require('./routes/ws.routes');
var app = express();
var server = require('http').createServer(app);
var expressWs = require('express-ws')(app);
expressWs.getWss().on('connection', function(ws) {
socketCollection.push({
id: 'someRandomSocketId',
socket: ws,
});
});
app.ws('/', SocketController.socketFunction);
Now every time new client connects to the server, it's reference will be saved to 'socketCollection'
You can access these clients from any module by importing this array
var socketCollection = require('./socketCollection');
var ws = findSocket('someRandomSocketId', socketCollection);
var findSocket = function(id, socketCollection) {
var result = socketCollection.filter(function(x){return x.id == id;} );
return result ? result[0].socket : null;
};
Can the following VB Script to open an IP cash drawer be done in Javascript instead?
Private Sub CashDrawerConnect_Click()
Winsock1.Close
ipaddr = "192.168.2.5"
Winsock1.RemoteHost = ipaddr
Winsock1.RemotePort = 30998
Winsock1.Connect
Sleep 250
TxtOpStatus = "Connection to the cash drawer at " & ipaddr & " is established..."
TxtOpStatus.Refresh
End Sub
Private Sub CashDrawerOpen_Click()
If Winsock1.State = sckConnected Then
Winsock1.SendData "opendrawer\0a"
Else
TxtOpStatus = "Not connected to the device"
TxtOpStatus.Refresh
End If
End Sub
You could do it on javascript, but not while running on a browser.
You would need to install nodejs and run your js file directly from the console.
This is a small example that would connect you the the drawer and send the "opendrawer" command on your example:
var net = require('net');
var client = net.connect({port: 30998, host: "yourip"}, function() {
client.write("opendrawer\0a");
});
If however the server has access to the drawer the javascript code could just make a request to the server which would be on charge of opening the connection to the drawer and sending the payload (opendrawer).
If you use php you can take a look at the sockets documentation.
Using VB and JavaScript the calls are mostly the same, you just jhave to adapt it to the language. http://www.ostrosoft.com/oswinsck/oswinsck_javascript.asp
The following is a snippet that uses WinSock from JScript
var oWinsock;
var sServer = "192.168.2.5";
var nPort = 3098;
var bClose = false;
oWinsock = new ActiveXObject("OSWINSCK.Winsock");
// Hooking up handlers
WScript.ConnectObject(oWinsock, "oWinsock_");
oWinsock.Connect(sServer, nPort);
WScript.Echo("Invalid URL");
bClose = true;
function oWinsock_OnConnect() {
oWinsock.SendData('Your data');
}
function oWinsock_OnDataArrival(bytesTotal) {
var sBuffer = oWinsock.GetDataBuffer();
sSource = sSource + sBuffer;
}
function oWinsock_OnError(Number, Description, Scode, Source,
HelpFile, HelpContext, CancelDisplay) {
WScript.Echo(Number + ': ' + Description);
}
function oWinsock_OnClose() {
oWinsock.CloseWinsock();
WScript.Echo(sSource);
oWinsock = null;
bClose = true;
}
while (!bClose) {
WScript.Sleep(1);
}
In the browser? Not really, but you can use WebSockets http://en.wikipedia.org/wiki/WebSocket
You'll need to implement a WebSocket server, so if you need to talk directly to a socket, you can't do it from a browser. But you could implement a proxy server that relays information between the socket server and the WebSocket server.
If you don't need two way communication, the best thing would be for your server to provide a webservice that wraps that socket request. Then your client can just make an AJAX call.