trying to connect to TCP server using Node.js - node.js

I'm trying to connect to a server/specific port using Node.js, and I don't even get past var net = require('net');
I'm using Node.js v16.15.0.
Welcome to Node.js v16.15.0.
When I use the command above, I receive UNDEFINED. As far as I know, I've installed everything I need (including socket.io), and I'm working within the Node.js environment in iTerm.
My goal is to connect to a TCP server, receive a list of files, and then download each of them over a persistent socket. But I'm a little stuck as I can't even seem to get into the TCP server in the first place.
This is what I think I'm supposed to run to get in (obviously with my correct port and IP info which is omitted below).
var HOST = 'IP';
var PORT = 'PORT'
var FILEPATH = 'myfilepathhereIwilltweakitwhenIgettothispoint';
Can anyone point me in the right direction?

From what you said, I think you are trying to code NodeJS script within the NodeJS executable start in command line. You get an UNDEFINED because you imported the library into your variable and this assignment does have any value, so it is UNDEFINED. You can read more about this in this subject : link
But what we usually do in NodeJS development is creating a file, let's call it index.js. Inside that file we are writing our code, let's say :
const net = require('net');
const client = net.createConnection({ port: 8124 }, () => {
// 'connect' listener.
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
Code sample from NodeJS Documentation.
Then we want to run our code by using the command line like this : node path/to/index.js.
Hope it helps !

Related

NodeJs text file writing

I am trying to write a text file from NodeJs. I have server running on my laptop. Currently, i am running client on my laptop and it works fine. But if i run same NodeJs client on Linux running on raspberrypi, it doesn't write on file or neither it gives any error.
I have the following code for client
var ioC = require('socket.io-client'),
ioClient = ioC.connect('http://localhost:4000'),
fs = require('fs'),
os = require('os');
ioClient.on('connect', function () { console.log("socket connected"); });
ioClient.on('ChangeState', function(msg){
console.log(msg);
fs.writeFile('server.txt', JSON.stringify(msg), function (err){
if (err) return console.log(err);
});
});
Can anybody please help me what can be the issue with this?
You are connecting to localhost which won't work if the client is on a different machine. You need to change the server to listen to the ip address your server has in your network, and also need to let your client connect to this ip. You can get the ip by running ifconfig in your terminal. Then (depending on wireless or wired connection) look for something like (usually the last paragraph):
and create the server on this ip. E.g.
192.168.178.30:4000
and connect to the same address from your client.
To find your ip on windows, refer to this guide

Connecting a Node JS Socket Server on Heroku to a front end client

I am having trouble getting a front end client to connect to my back end Node JS server on HEROKU. I am aware that heroku uses process.env.PORT to decide which port you can route socket traffic through, but due to the fact that my client will not be hosted on the same server I will not be able to access this ever-changing environment variable. I was wondering if there is any workaround for this problem which would let my front end client connect to my socket on Heroku without having to know the port ahead of time.
Relevent Node Code
var net = require('net');
var port = process.env.PORT || 9001
var mySocket;
var serverF = net.createServer(function(socket) {
mySocket = socket;
mySocket.on("connect", onConnect);
mySocket.on("data", onData);
});
function onConnect()
{
console.log("Connected to Flash");
}
serverF.listen(port);
function onData(d)
{
if(d == "exit\0")
{
console.log("exit");
mySocket.end();
server.close();
}
else
{
console.log(d);
mySocket.write(d, 'utf8');
}
}
I am trying to use flash as my front-end client, but I tried to simplify and wrote a basic client in node to run to isolate the problem and ran into the same issue.
This is a continuation of an ongoing problem I have that can be found here: https://stackoverflow.com/questions/32601186/creating-a-socket-server-with-nodejs-on-heroku-with-flash-as-the-client
No, you can not just "know" where it's running. You can, however set up a central registry somewhere with the port information listed. sort of a service registry 'lite'.
Just publish a static site somewhere with the port information, then request that static source first. Once you've parsed the info there, you're good to go.
Or, if you have the resources, set up a reverse proxy somewhere that will always be available, and that you can use to change your dynamic back-end.

How to use the net module from Node.js with browserify?

I want to use the net module from Node.js on the client side (in the browser):
var net = require('net');
So I looked up how to get Node.js modules to the client, and browserify seems to be the answer. I tried it with jQuery and it worked like a charm.
But for some reason the net module does not want to work. If I write require('jquery') it works fine, but if I write require('net') it does not work, meaning my bundled .js file is empty.
I tried to search for something else, but the only thing I found is net-browserify on Github. With this, at least my bundle.js file is filled, but I get a JavaScript error using this (it has something to do with the connect function).
This is my code which works on the server side just fine:
var net = require('net-browserify');
//or var net = require('net');
var client = new net.Socket();
client.connect({port:25003}, 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');
});
I assume that net-browserify lets you use a specific connect function, but I don't know which.
How can I use the net module from Node.js on the client side?
This is because net gives you access to raw TCP sockets - which browsers simply cannot do from the JavaScript end. It is impossible for net to ever be ported to the client side until such an API is written (allowing arbitrary tcp traffic).
Your best bet if you want to send tcp data from the client to the server is using web sockets using the socket.io module or the ws one.
Your best bet if you want clients to communicate directly is to look into WebRTC

Connecting to socket.io server

I'm trying to get this exmaple working on my own computer:
https://github.com/tamaspiros/simple-chat
I have node.js installed and have installed socket.io as well. The readme is informing me to change the IP addresses on these two lines:
var socket = io.listen(1223, "1.2.3.4");
var socket = io.connect("1.2.3.4:1223");
However, I'm not really sure what to change the IP addresses into. I would like to get the simple chat box application working on my own computer.
You just need to configure it in one like, for ie:
var socket = io.connect('adress:port');
where addres is Your socket.io server IP or hostname, and yyyy is port on which it listens.
after that, You can get and emit events with:
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
on server listen for
and thats it.
Before making chat You can try just using this example from official socket.io: link
PS dont forget to add socket.io client file source on client side! :). The whole code should look like in the example in the provided link.

How to socket.io emitting and receiving simple data?

I've been playing around with socket.io (very much a newbie), my goal is to post data to the server, do a small database entry and return data to the user real time.
My default server is nginx currently.
I've been looking at the example on socket.io, but this is only when wanting to use node.js to handle everything.
When trying to listen on port 3000, I get a warning of:
server:
var io = require('socket.io').listen(3000);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I simply want to push the data from my web page to the node server, but whenever I do currently, I get a 404 for the socket.io/socket.io.js file. I've looked in to this, and other answers suggest having an update to date version of the node module express? I've ensured I have the latest versions of node.js, socket.io and express installed on my server.
Is there anywhere obvious where I'm going wrong here, sorry if this is an obvious question.
Assuming you're running a Linux machine, there are two problems. For one, Nginx will already be running on port 80. Therefore, you can't run another process on that port, and should either run Node.js on another port, or follow a setup like this.
The other problem is that you need root access to use the ports < 1024 on a Linux machine. Without proper permission, you will get the EACCES error you're seeing.
Once the server binds properly, the socket.io.js file will no longer return a not found error.

Resources