I am creating a socket pass through inspector.
Basically, I start up a socket server (net.createServer) and a socket client (net.connect). For testing purposes, I do not have a endpoint socket waiting.
I want test whether the endpoint socket is available. If not, nodejs should wait until socket is available.
var net = require('net');
var inbound = net.createServer();
var outbound = net.connect({
port: 8193
});
inbound.listen(8192, function () { //'listening' listener
address = inbound.address();
console.log('Server started on %j', address);
});
inbound.on('connection', function (insock, outbound) {
console.log('CONNECTED ' + insock.remoteAddress + ':' + insock.remotePort);
insock.on('data', function (data, outbound) {
outbound.write(data);
console.log('DATA ' + data);
});
});
The best way to test whether any resource is available is to try to use it. Pre-testing is liable to a number of objections:
If it tests something different from the actual usage, it may yield an incorrect answer.
If it tests the same things as the actual usage it is merely wastefully redundant.
The situation may change between the test and the usage.
Related
I've read through the site and googled, and can't seem to find an answer that will work for me.
I've set up a super super basic example of using Socket.IO until I can get my head around, all it does is passes a number to the back end, adds +1 and send it back to front end.
It does work however, each interval round, it emits more and more (which I can see using console.log on the server side.) I'm only connected using one computer to test.
Can someone help me please. I understand its probably because the emit is inside the connection but I just can't quite click in my head on how to overcome this.
I've tried moving bits around, moving the function out of the connection. I've tried multiple ideas from google, but nothing seems to solve it.
const io = require('socket.io')();
io.on('connection', (socket) => {
socket.on('subscribeToAddition', (additon,interval) => {
console.log('current number... ', additon);
setInterval(() => {
socket.emit('addition', additon+1);
}, interval);
});
});
const port = 8000;
io.listen(port);
console.log('listening on port ', port);
the interval variable is set as 5 seconds in my react component. I just want it to log/update once every five seconds instead of log once, then twice, then 4 times, then 8 times, etc
Given the symptoms, it's likely that you're sending the subscribeToAddition event more than once on the same socket and thus starting more than one timer for the same socket and thus you get duplicate messages.
Proper indentation of your code makes things a little clearer:
const io = require('socket.io')();
io.on('connection', (socket) => {
socket.on('subscribeToAddition', (additon, interval) => {
console.log('current number... ', additon);
setInterval(() => {
socket.emit('addition', additon + 1);
}, interval);
});
});
const port = 8000;
io.listen(port);
console.log('listening on port ', port);
I want to make sure you understand that setInterval() starts a repeating timer that goes forever until you call clearInterval() on the timerId that it returns.
Problems I see:
In every subscribeToAddition message, you're adding a new setInterval() timer. So, if you send the subscribeToAddition twice, you will have two setInterval() timers each going on the same socket.
Those setInterval() timers will accumulate and never go away because you have no way of the client stopping them and they don't go away even when the socket closes. They will just cause errors because socket.emit() won't work on a closed socket, but they will probably even prevent garbage collection of the old socket.
It is not clear exactly how you want this to work, but here's a cleaned up version:
const io = require('socket.io')();
io.on('connection', (socket) => {
function clearTimer() {
if (socket.myTimer) {
clearInterval(socket.myTimer);
delete socket.myTimer;
}
}
socket.on('subscribeToAddition', (additon, interval) => {
console.log('current number... ', additon);
// don't start a new interval timer if one is already running
if (!socket.mytimer) {
socket.mytimer = setInterval(() => {
socket.emit('addition', ++additon);
}, interval);
}
});
socket.on('unSubscribeToAddition', () => {
clearTimer();
});
socket.on('disconnect', () => {
clearTimer();
});
});
const port = 8000;
io.listen(port);
console.log('listening on port ', port);
This version makes the following modifications:
Keeps track of the timerID from setInterval() so we can stop it in the future. For convenience, we store it as a custom property on the socket object so that each connected socket has its own timer.
Adds an unsubscribeToAddition message so the client can stop the timer.
Adds a disconnect message handler so you can stop the timer when the socket disconnects.
Increments the additon variable on each tick of the timer.
I have code to log every connection to my HTTP-server on a socket level and also log any incoming data.
This code was originally written for NodeJS 0.8 and works good there.
No my project is migrated to 0.10.24 and socket logging code stopped working.
Here is my code:
var netLogStream = fs.createWriteStream('net.log');
(function(f) {
net.Server.prototype.listen = function(port) {
var rv = f.apply(this, arguments); // (1)
rv.on('connection', function(socket) { // (2)
socket.on('data', function(data) {
data.toString().split('\n').forEach(function(line) { // (3)
netLogStream.write('... some logging here ... ' + line);
});
});
});
return rv;
};
})(net.Server.prototype.listen);
On 0.10 I can get to (1) and get Socket instance on (2) but I never get to (3). Same time my whole application works fine without any issues.
ADD: My server is created with Express#3.4.x
I'm not sure why the results are different between node v0.8 and v0.10, but if I had to guess, I'd be looking at the return value of net.Server.prototype.listen.
According to the documentation, this is an asynchronous method which emits the 'listen' event and invokes its callback when the listening is bound. You're not looking for that event, but rather, capturing the return value of listen, which for an async function, may not be well-defined. It's obviously not null or undefined since you don't get a runtime error, but the return value may not be the same between v0.8 and v0.10.
I honestly don't know for sure because I don't do low-level socket coding, but I have 2 suggestions to try:
Since the connection event is emitted from the Server object, perhaps you need this.on instead of rv.on.
Setup the connection event listener before you invoke listen just to minimize risk of race conditions.
Try this and see what happens:
var netLogStream = fs.createWriteStream('net.log');
(function(f) {
net.Server.prototype.listen = function(port) {
this.on('connection', function(socket) { // (2)
socket.on('data', function(data) {
data.toString().split('\n').forEach(function(line) { // (3)
netLogStream.write('... some logging here ... ' + line);
});
});
});
return f.apply(this, arguments); // (1)
};
})(net.Server.prototype.listen);
I'm new to Node.js and I am writing a client to consume a text-based TCP stream from a server. For testing purposes, I want to simulate the server in Node so I can test with no other dependencies.
I have a file of captured data that looks like:
$X,... <-- broadcast every second
$A,...
$A,...
$B,...
$X,... <-- broadcast every second
$A,...
$A,...
$C,...
$X,... <-- broadcast every second
The server emits a line starting with $X every second. The other records are broadcast as events happen. How can I modify my network server below to broadcast this data and throttle it so it emits one line at a time and pauses for one second every time it encounters a line starting with $X?
Here is my code so far which reads in the data and broadcasts it over a port:
var http = require('http')
, fs = require('fs')
;
var server = http.createServer(function (req, res) {
var stream = fs.createReadStream(__dirname + '/data.txt');
stream.pipe(res);
});
server.listen(8000);
console.log('server running on 8000');
This works but obviously just streams out the whole file at warp speed. What I want is to spit out all of the lines from one $X to the next, pause for one second (close enough for testing purposes) and then continue to the next $X and so on like:
> telnet 127.0.0.1 8000
$X,...
$A,...
$A,...
$B,...
(output would pause for one second)
$X,...
$A,...
$A,...
$C,...
(output would pause for one second)
$X,...
...
In my example above, the broadcast always starts from the beginning of data.txt when I connect with a client. Ideally, this server would keep broadcasting this data in a loop, allowing clients to disconnect and reconnect at any time and start receiving data wherever the server simulator was currently at.
(PS - data.txt is a relatively small file, < 1MB in most cases)
UPDATE -
Thanks to Laurent's pointer, I was able to get it working with the following:
var net = require('net'),
fs = require('fs'),
async = require('async');
var server = net.createServer(function (socket) {
var lines = fs.readFileSync(__dirname + '/data-small.txt').toString().split(/\n+/);
async.whilst(
function () {
return lines.length > 0;
},
function (done) {
var line = lines.shift();
socket.write(line + '\r\n');
setTimeout(done, /^\$X,/.test(line) ? 1000 : 0);
},
function (err) {
// no more lines present
socket.end();
});
});
server.listen(8000);
console.log('server running on 8000');
I'm now getting a blast of lines until an $X, a 1s pause, and then it continues! Thanks!
Drilling into my 2nd part: is there a way to synchronize output of this faux server so all clients see the same output regardless of when they connect?
If you want to keep all clients in sync, you need to do something entirely different. Here's a starting point. Also, it seems like the net module would be a better fit.
var net = require('net'),
fs = require('fs'),
_ = require('underscore');
var current = 0,
sockets = [];
// dirty parser for blocs
var data = fs.readFileSync(__dirname + '/data.txt').toString(),
blocs = _.chain(data.split(/\$X,/)).compact().map(function (bloc) {
return '$X,' + bloc;
}).value();
function streamBloc() {
console.log('writing bloc #' + current + ' to ' + sockets.length + ' sockets');
_(sockets).each(function (socket) {
socket.write(blocs[current]);
});
current = (current + 1) % blocs.length;
setTimeout(streamBloc, 1000);
}
var server = net.createServer(function (socket) {
console.log('incoming connection');
// immediately write current bloc
socket.write(blocs[current]);
// add to sockets so that it receive future blocs
sockets.push(socket);
// cleanup when the client leaves
socket.on('end', function () {
sockets = _(sockets).without(socket);
});
}).listen(8000, function () {
console.log('server listening on port 8000');
});
streamBloc();
Trying to send data from a serial device to web clients. I am using a serial to network proxy, ser2Net to make the data available to a server that acts on the data and sends a manipulated version of the data to web clients. The clients specify the location of the ser2net host and port. The core of this action is coded in node.js as shown here:
function getDataStream(socket, dataSourcePort, host) {
var dataStream = net.createConnection(dataSourcePort, host),
dataLine = "";
dataStream.on('error', function(error){
socket.emit('error',{message:"Source not found on host:"+ host + " port:"+dataSourcePort});
console.log(error);
});
dataStream.on('connect', function(){
socket.emit('connected',{message:"Data Source Found"});
});
dataStream.on('close', function(){
console.log("Close socket");
});
dataStream.on('end',function(){
console.log('socket ended');
dataConnection.emit('lost',{connectInfo:{host:host,port:dataSourcePort}});
});
dataStream.on('data', function(data) {
// Collect a line from the host
line += data.toString();
// Split collected data by delimiter
line.split(delimiter).forEach(function (part, i, array) {
if (i !== array.length-1) { // Fully delimited line.
//push on to buffer and emit when bufferSendCommand is present
dataLine = part.trim();
buffer.push(part.trim());
if(part.substring(0, bufferSendCommand.length) == bufferSendCommand){
gotALine.emit('new', buffer);
buffer=[];
}
}
else {
// Last split part might be partial. We can't announce it just yet.
line = part;
}
});
});
return dataStream;
}
io.sockets.on('connection', function(socket){
var stream = getDataStream(socket, dataSourcePort, host);
//dispense incoming data from data server
gotALine.on('new', function(buffer){
socket.emit('feed', {feedLines: buffer});
});
dataConnection.on('lost', function(connectInfo){
setTimeout(function(){
console.log("Trying --- to reconnect ");
stream = getDataStream(socket, connectInfo.port, connectInfo.host);
},5000);
});
// Handle Client request to change stream
socket.on('message',function(data) {
var clientMessage = JSON.parse(data);
if('connectString' in clientMessage
&& clientMessage.connectString.dataHost !== ''
&& clientMessage.connectString.dataPort !== '') {
stream.destroy();
stream = getDataStream(socket,
clientMessage.connectString.dataPort,
clientMessage.connectString.dataHost);
}
});
});
This works well enough until the serial device drops off and ser2net stops sending data. My attempt to catch the end of the socket and reconnect is not working. The event gets emitted properly but the setTimeout only goes once. I would like to find a way to keep on trying to reconnect while sending a message to the client informing or retry attempts. I am node.js newbie and this may not be the best way to do this. Any suggestions would be appreciated.
Ok I think I figured it out in the dataStream.on('data' ... I added a setTimeout
clearTimeout(connectionMonitor);
connectionMonitor = setTimeout(function(){doReconnect(socket);}, someThresholdTime);
The timeout executes if data stops coming in, as it is repeatedly cleared each time data comes in. The doReconnect function keeps trying to connect and sends a message to the client saying something bad is going on.
I have a Node.js-Server with a socket.io-connection to a browser-client. sometimes the connection gets interrupted, for example, when I need to restart the server. When that happens, how can the client know this?
Here's an example on how you can achieve that on the client side:
var chat = io.connect('http://localhost:4000/chat');
chat.on('connect', function () {
console.log('Connected to the chat!');
});
chat.on('disconnect', function () {
console.log('Disconnected from the chat!');
});
As you can see, you keep the connection variable and you use connection_variable.on('disconnect', callback_function_here)