telnet using node js - node.js

1.I have tried using node js to connect telnet. I am trying to control the Epson projector using node js and telnet from my computer.
2.I am running the js code in cmd by: "node filelocation\test.js"
The code i used:
const telnet = require('telnet-client');
const server = new telnet();
// display server response
server.on("data", function(data){
console.log(''+data);
});
// login when connected
server.on("connect", function(){
server.write("%1POWR 1\r\n");
});
// connect to server
server.connect({
host: "192.168.2.170",
port: 4352
});
I am running the js code in cmd by: "node filelocation\test.js"
The error i get is :
TypeError: server.write is not a function
at Telnet.<anonymous> (C:\Users\USER\Desktop\TEST\telnet2.js:11:12)
at Telnet.emit (events.js:314:20)
at Socket.<anonymous> (C:\Users\USER\node_modules\telnet-client\lib\index.js:70:16)
at Object.onceWrapper (events.js:420:28)
at Socket.emit (events.js:326:22)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1132:10)

I used this code and it worked for me. Thanks all for the support.
var net = require('net');
var client = new net.Socket();
client.connect(4352, 'x.x.x.x', function() {
console.log('Connected');
client.write('%1POWR 0\r\n');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});

I checked this package and there are no write() function available to use. Instead use exec(). Also change on('connect') like below to catch the errors.
server.on("connect", function(err, param){
server.exec("%1POWR 1\r\n");
});

Related

connect EADDRINUSE: cannot use node.js tcp client localPort after reconnecting within 30 seconds?

I have created a tcp server and a tcp client.
In my tcp client, I have specified the localPort because I want to use some specific ports in case of reconnection.
Below is my tcp server and client's code
TCP SERVER
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
socket.on('error', function(err){
console.log('on socket error', err);
})
});
server.on('error', function(err){
console.log('on error',err);
})
server.listen(1337, '127.0.0.1');
TCP CLIENT
var net = require('net');
var client = new net.Socket();
client.connect({port: 1337, host: '127.0.0.1', localPort: 10002}, function() {
console.log('Connected');
client.write('Hello, server! Love, Client.');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
client.on('error', function(err) {
console.log('error in connection',err);
});
I have this server and client in two separate files.
If I run the server, and then run the client for the first time, everything works fine.
But as soon as I re-run(reconnect) the client, it gives me an error
{ Error: connect EADDRINUSE 127.0.0.1:1337 - Local (0.0.0.0:10002)
at internalConnect (net.js:964:16)
at defaultTriggerAsyncIdScope (internal/async_hooks.js:281:19)
at net.js:1062:9
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)
at Function.Module.runMain (module.js:696:11)
at startup (bootstrap_node.js:204:16)
at bootstrap_node.js:625:3
errno: 'EADDRINUSE',
code: 'EADDRINUSE',
syscall: 'connect',
address: '127.0.0.1',
port: 1337 }
It works fine if I retry after around 30 seconds.
Does net in nodejs have a TIMEOUT of not using the same localPort for 30 seconds?
If it is so, can we reduce it or manage it somehow?

Node.js app fails to connect using socket.io-client

Background
I have a Node.js server using socket.io that accepts connections from clients via HTTPS.
I know this server works as I am able to connect to it via browser.
Problem
The problem is that I can't create a node app to connect to this server as a client.
I am using the following code:
const io = require("socket.io-client");
const socket = io.connect("https://my.website.com:3002", { secure: true, reconnect: true });
socket.on("connect", function(){
console.log("connected");
});
socket.on("disconnect", function(){
console.log("disconnected");
});
socket.on("error", console.error);
The server registers no connections, and this app logs no errors. It would seem that I am connecting to the wrong server, but this same URL works just fine when I use a browser.
Research
I have searched github and the official docs for an answer. Even similar questions from stackoverflow seem to not work:
Node.js client for a socket.io server
https://www.npmjs.com/package/socket.io-client
https://github.com/socketio/socket.io-client/issues/828
Question
What am I doing wrong ?
Answer
After realising, that not all errors feed into the "error" event ( special thanks to #RolandStarke ) I found that I was having a consistent XHR pool request:
{ Error: xhr poll error
at XHR.Transport.onError (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transport.js:64:13)
at Request.<anonymous> (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transports/polling-xhr.js:128:10)
at Request.Emitter.emit (/Users/pedro/Workspace/backend-stresser/node_modules/component-emitter/index.js:133:20)
at Request.onError (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transports/polling-xhr.js:310:8)
at Timeout._onTimeout (/Users/pedro/Workspace/backend-stresser/node_modules/engine.io-client/lib/transports/polling-xhr.js:257:18)
at ontimeout (timers.js:469:11)
at tryOnTimeout (timers.js:304:5)
at Timer.listOnTimeout (timers.js:264:5) type: 'TransportError', description: 503 }
Once I had this information, I made a quick search and found a solution to this issue, which seems to be a bug:
https://github.com/socketio/socket.io-client/issues/1097
The code I am now using is:
const socket = io.connect("https://my.website.com:3002", { secure: true, reconnection: true, rejectUnauthorized: false });
And it works as expected.
I have used this code in my client side and it worked:
import io from "socket.io-client"
const SERVER = "http://localhost:5000"
const socket = io(SERVER, { transports: ["websocket"] })

How to create a Node.js Unix socket client when server might not be available yet

I'm having trouble getting my Node.js Unix socket stood up. The Node.js code spawns a C app that acts as the server. The server might not be ready by the time I start trying to connect to it from the Node.js code, so I get an error. I even try to naively catch it, but it doesn't work. Here's a simplified version of the code:
var net = require('net');
const URI_SOCK = '/opt/tmp/.socket';
try {
const socket = net.connect(URI_SOCK, function() {
//'connect' listener
console.log('Connected to socket!');
socket.write("42");
});
} catch(err) {
console.log("Caught you!");
}
Here's what happens when I try to run it:
✘ ⚡ ⚙ root#ncooprider-tron  ~  node test.js
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
Any ideas for how to catch that error or what to do so I can force the program to wait until the server is ready to receive clients?
This has been answered a few times before, but you basically need to listen to the "error" event the client emits. Something like:
socket.on('error', function(err) {
console.log("Error: " + err);
});

http request to a different app in a different port

I have 2 nodejs apps one running in port 8000 that only returns "hello"
and another app running on port 3000 that makes a simple http request to the first app
var http = require('http');
var r = http.get({
host: 'localhost',
path: '/',
port: '8000'
},
function(response) {
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
console.log(body);
});
});
the console log returns
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:874:11)
at exports._exceptionWithHostPort (util.js:897:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
What´s the problem here?
the first app is running correctly in http://localhost:8000/ but for some reason
when the second app makes a request to the first app I get the error I posted above. thanks for your help.
Seems like first app (on port 8000) is not reachable or not started at the moment, when second app sends request.

Can't get node app to run on openshift, Error: listen EACCES

I have been trying to fix this for hours, with endless googling, I try to start the app, go to the url and see a 503 Service Unavailable error, I then cd into app-root/repo, try to manually start server.js, and get the following:
[my-app-url.rhcloud.com repo]\> node server.js
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
Connecting to server
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1039:14)
at listen (net.js:1061:10)
at net.js:1143:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:902:3
This is driving me insane, all I'm trying to do is a simple api, and it works perfectly in my local environment.
Thank you.
Already another program or instance of this program is running on same port.
run - sudo netstat -tapen | grep ":<<your given port>>"
and then kill the process.
Then try to run the server...
Thanks
You need to bind to the OPENSHIFT_NODEJS_IP, i see you are only binding to the correct port, not the ip also: https://developers.openshift.com/en/node-js-getting-started.html
https://github.com/openshift-quickstart/openshift-nodejs-http-and-websocket-example/blob/master/server.js#L1
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var WebSocketServer = require('ws').Server
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Welcome to Node.js on OpenShift!\n\n");
response.end("Thanks for visiting us! \n");
});
server.listen( port, ipaddress, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wss = new WebSocketServer({
server: server,
autoAcceptConnections: false
});
wss.on('connection', function(ws) {
console.log("New connection");
ws.on('message', function(message) {
ws.send("Received: " + message);
});
ws.send('Welcome!');
});
console.log("Listening to " + ipaddress + ":" + port + "...");

Resources