I have a ws.js which is my server:
// A simple server-side script.
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 3000 });
let number = 0.0;
function updateNumber(){
number = Math.random().toFixed(4);
}
// Desperetly tried this.
var emitter = function() {}
var emission = function(data) {
emitter(data);
}
// Then my WebSocket stuff.
wss.on('connection', function(ws) {
emitter = function(data) {
wss.clients.forEach(function(client) {
// ---> How to constantly run updateNumber()
// As long as connection is live.
console.log(data);
// Debug
console.log('[server:onConnect] Received request.');
// Send the transmission.
console.log('[server:onConnection] Sending:', number);
client.send(number);
});
}
});
I have to do this without using setInterval() as the number will be coming from a file that is constantly being updated.
So in my server's verbosity stream, in the terminal I get this, once the client connects in:
[server:onConnection] Sending: 0.9569
[server:onConnect] Received request.
[server:onConnection] Sending: 0.4058
[server:onConnect] Received request.
[server:onConnection] Sending: 0.7813
[server:onConnect] Received request.
[server:onConnection] Sending: 0.9672
[server:onConnect] Received request.
[server:onConnection] Sending: 0.0671
[server:onConnect] Received request.
[server:onConnection] Sending: 0.5682
[server:onConnect] Received request.
[server:onConnection] Sending: 0.0171
--- UPDATE ---
The problem is fixed when I tweaked the updateNumber() function as:
function updateNumber(){
number = Math.random().toFixed(4);
emission();
}
This seems to be successfully bridging the emitter function burred inside the on connect block and the updateNumber() function.
However, this solution still requires a setInterval() to run the updateNumber() in order to create the emission of a constantly changing number. Is there a way to create a function that runs and constantly emits a random number, without using setInterval().
https://www.linode.com/docs/development/introduction-to-websockets/
This article can help you to understand websocket correctly and how you can listen functions without setInterval
Related
I'm definitely a newbie with JS and node. I have telescope management software called SkyX Pro, and it has the ability to run a TCP Server on port 3040. I can connect to it using Netcat and hand it a Javascript starting with //* Javascript *// this works and allows me to startup cameras and other equipment and send commands for taking pictures etc. The issue is it needs to be run from a batch file which makes getting any information back to an HTML page tough (Like Camera, focuser and filter wheel status and temperatures).
The NC call looks like "NC localhost 3040 < Javascript-file.js
To get around the browser to local machine security issues I want to run this from node.js with maybe socket.io-client if possible, but I don't know the proper syntax for it.
I have seen plenty of client syntax sending hello's etc. but nothing send javascript and allowing for two-way connectivity that I can understand.
I have tried using:
var socket = io.connect('http://localhost');`enter code here`
socket.on('httpServer', function (data) {
console.log(data);
document.write(data + "\r\n");
socket.emit('tcp', "For TCP");
});
const net = require('net');
const client = new net.Socket();
client.connect({ port: 3040, host: process.argv[2] });
client.on('data', (data) => {
console.log(data.toString('utf-8'));
But I do not understand it well enough to troubleshoot why it's not working.
Any help would be wonderful, and please treat me like a baby that needs its step by step.
Cheer
Peter
Reading [1], We can assume socket-io isn't the perfect fit for you, because that Server you have sound like a typical tcp-socket server, not a socket.io server ( which requires special headers ) or a web-socket server.
So you only needs "net" library to do the job.
const net = require('net');
// module to send a message to TCP-socket server and wait for the response from socket-server
const sendAndReceive = async (client, message) => {
client.write(message);
let response = null
await ( new Promise( (resolve, reject) => {
client.on('data', function(data) {
response = data;
resolve()
});
}))
return response;
}
// send a single message to the socket-server and print the response
const sendJSCode = (message) => {
// create socket-client
const client = new net.Socket();
client.connect(3040, 'localhost', async function() {
console.log('Connected');
// send message and receive response
const response = await sendAndReceive(client, message)
// parse and print repsonse string
const stringifiedResponse = Buffer.from(response).toString()
console.log('from server: ', stringifiedResponse)
// clean up connection
client.destroy()
});
}
sendJSCode('var Out; \n Out="TheSky Build=" + Application.build \n\r')
This script will:
Initiate a socket client
on connection successfully, client sends a message
client receives back response from that message
client prints response to terminal
Note that TheSkyX has a limitation of 4096 bytes for each message[2], any more than that and we will need to chunk the message. So you may want to keep the js-code short and precise.
that snippet I gave is minimal, it doesn't handle errors from server. If you want, you can add client.on("error", .. ) to handle it.
Your point of connecting to the socket server directly from browser is very intriguing, unfortunately it is not allowed by modern browsers natively due to security concerns 3
[1] https://socket.io/docs/#What-Socket-IO-is-not:~:text=That%20is%20why%20a%20WebSocket%20client,to%20a%20plain%20WebSocket%20server%20either.
[2] https://www.bisque.com/wp-content/scripttheskyx/scriptOverSocket.html#MSearchField:~:text=set%20to%204096%20bytes
I'm sending out a lot of requests to another server, and want to limit them so as to not overload the server. My impression is that this can be done with the pool parameter in options, but I'm not sure if I'm doing so properly.
I'd like to be able to keep track of when the requests are sent out, as I'm trying to establish a duplex connection, and need to make sure the corresponding GET and POST requests are sent out at the same time.
Here's a simplified example of what I'm trying:
var request = require('request');
var options = {
'url': 'http://www.google.com',
'pool': {
'maxSockets': 3
}
};
for (var i = 0; i < 100; i++) {
request.get(options, (function(j) {
return function(err, res, body) {
console.log(j);
}
})(i));
}
Is there an event emitted when the requests are actually sent out? Is there any way for me to track when, and in what order each request is being sent out?
I found this in the Node.js documentation:
Event: 'socket'#
function (socket) { }
Emitted after a socket is assigned to this request.
You can use it to monitor connections as they are assigned sockets like this:
http.get(options, function(res) {
// Do stuff
}).on("socket", function (socket) {
socket.on("connection") {
// record connection
};
});
The same event is emitted with the request library, since it's just a wrapper around the builtin http module.
This Is my code client socket.io, im trying to emit data and callback to server
_this.emitHandler = function(event, data, callback){
var packet = {};
if(data){
packet.data = data;
}
if(callback){
packet.callback = callback;
}
io.emit(event, packet); // emit packet to server with data and callback
}
and when i console.log my packet its just print data, the callback disappeared. this is my server code
io.on('*', function(socket, args, next){
console.log(args) // this args just print data in console
}
im using socket.io-event btw to capture all event, is something wrong with my code?
You can't send function like that.
What you can do is to JSON.stringify it and on the server call eval() on it.
Remember that it's dangerous. Anybody could send some code to your server and execute it.
I learned to make request with the XMPPserver by using node-xmpp library. Now i can make the request as mentioned in XMPP extensions documentations. But now i want to get the callback response for the each request (especially the XML response).
Here i have used the following code the make a request subscription (friend request) to a another user
var net = require("net");
var xmpp = require('node-xmpp');
var cl = new xmpp.Client({ jid: "one#localhost", password: "comet123$" })
cl.addListener('online', function(data) {
console.log('Connected as ' + data.jid.user + '#' + data.jid.domain + '/' + data.jid.resource)
//making subscription
var stanza = new xmpp.Element('presence',{
to: "hai#localhost",
from: "one#localhost",
type: "subscribe",
}).up
// making request
cl.send(stanza);
// nodejs has nothing left to do and will exit
cl.end()
})
I want to know, how to get the response result.
I tried with the callback functionality with as llike this,
cl.send(stanza, function(result){
console.log(result);
});
and also like this
var result = cl.send(stanza);
This returns only true,
So can anyone please tell me how do I get the callback result for the requests that we make by using the node-xmpp libarary
There is no callback or return for XMPP messages. You will have to have to set up an event listener to pick up messages coming back from the server. Add:
cl.on('stanza', function(stanza){
// Do something with the stanza
// If you want to end after the first message you get back, move this here
cl.end();
});
you can get raw data from connection
cl.connection.on("data", function (data) {
console.log('data', data.toString('utf8'));
});
I want to have the following architecture:
A JSON REST API where real time statistic data is pushed to and stored in a Redis server.
A JSON REST API call where any number of clients (native or web) can receive this data after it has been stored - i.e. in real time.
The first client will just be a web app and I may build a native app later.
I'm wondering if my only option is for the clients to poll the REST API for changes? Ideally, I'd like the server to push updates as they arrive so I don't need to manage this polling.
Is my architecture suitable for what I want to achieve, or am I missing something?
A more efficient way than polling is to use websockets, such as Faye or Socket.IO. You can place an emit event under a data store event to immediately send data that's been stored.
With Socket.IO, you'd do that like this:
var io = require('socket.io').listen(80);
//note that you can listen on HTTP servers
//can also be used with Express applications, etc
//when data is stored, run this
io.sockets.emit('event', {
object: 'that is sent to client'
});
You could then use this to tell the client that there is new data, or you could directly send the newly stored data. Custom events can be defined, such as
io.sockets.emit('data_receive', function (data) {...});
and would be received client side like so:
var socket = io.connect('http://socket.location');
socket.on('data_recieve, function (data) {
//data is whatever sent from server
});
In Faye you'd do something like this:
var http = require('http');
var faye = require('faye');
var bayeux = new faye.NodeAdapter({
mount: '/faye',
timeout: 45
});
bayeux.listen(8000);
Then when data is stored, you'd run:
client.publish('/path', {
data: 'Hello world'
});
Any client that has created a client like so:
var client = new Faye.Client('http://socket:port/path');
client.subscribe('/path', function(data) {
alert('Received data: ' + data.text);
});
Will receive the data.
You have the option of Node.js and the websocket for push and pull in realtime.
To don't manage the queuing you still have the option of MQ.