NodeJs text file writing - node.js

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

Related

trying to connect to TCP server using 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 !

nodejs websockets connection from localhost works but remote doesnt

I'm running a simple websocket server in nodejs
const WebSocket = require('ws');
const wss = new WebSocket.Server({ host: '0.0.0.0', port: 13000 });
wss.on('connection', function connection(ws) {
console.log("new connection");
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.on('error', function(e) {
console.log('error', e);
});
ws.on('close', function(e) {
console.log('close', e);
});
ws.send('something');
});
I can connect to the server using:
s=new WebSocket('ws://localhost:13000')
and everything is fine. But if I try to connect from another computer:
s=new WebSocket('ws://serveripaddress:13000')
The server shows
new connection
close 1006
So I know that the client connects, but it then immediately disconnects. I am totally lost here, don't know how to diagnose my problem. Any ideas?
UPDATE
These scenarios work:
two ec2 instances: works
two linux VMs communicating over a host-only network: works
And these fail:
windows host machine and VM (host only network): fail
an ec2 instance and one of my VM's: fail
Here's the weird part, if I make a simple socket server using 'net', ALL scenarios above work! So it seems like its still a networking issue (since websockets work in some scenarios) but it is a networking issue specific to websockets (because socket server works where websocket doesnt)!
I dont have access to the firewall that my windows host machine is on so if that's the issue then I'm stuck. But I will try this all on a different host machine where I have access to the firewall.
But if it was the firewall, I would except it to work between the windows host and the VM because they are on their own virtual network...

Socket.io client can not connect to localhost while it can connect to 127.0.0.1

I have a server set up using node.js and I'm trying to connect to the server with socket.io. The server used to work perfectly 2 months ago but for some reason it does not work anymore. The server code looks like the following:
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
console.log ('Client connected.'); });
console.log ('Server started.');
server.listen(3000, '0.0.0.0');
On my client side, I'm using the line
socket = io.connect("http://localhost:3000");
to try to connect to my server, but it doesn't work. The connection works perfectly if I use the line
socket = io.connect("http://127.0.0.1:3000");
If I type localhost:3000 on the browser, it sends me to the page saying Hello World as intended, same as 127.0.0.1, so it is not working only when I'm using io.connect.
Things that I have tried are:
changing the host file (adding the line 127.0.0.1 localhost, removing the line including ::1, making a new host file and overwriting it)
trying it on a different machine, still the same problem
resetting the router settings.
pinging localhost on a cmd prompt, it says reply from ::1: time<1ms
installing different version of socket.io and node.js (both the most recent ones and versions 2 months ago)
Considering what happens from web browser, localhost seems to work but it only does not work when I use socket.io with it. I have been unable to solve this problem that suddenly appeared, so I would appreciate it a lot if someone can give me some insights on what can be causing this.
It seems like an IPv4/IPv6 issue. You may try changing this:
server.listen(3000, '0.0.0.0');
to this:
server.listen(3000, '::1');
or this:
server.listen(3000);

Socket.io client doesn't connect to server

I have developed a simple chat using socket.io on a vagrant environment and it works correctly.
When I try to run the chat on the production environment, the nodejs/socket.io server runs but the client doesn't even fire the connect event.
The only thing I've modified is, in the client side:
var socket = io.connect('http://localhost:3000');
to:
var socket = io.connect('http://ip_address:3000');
This is the server code:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
app.listen(3000, function() {
console.log('Server is running');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
socket.on('subscribe', function() {
console.log('subscribe request has arrived');
console.log(socket.id);
});
});
If it worked locally and stopped working after deployment, it's probably a network issue - firewall, blocked port, linux enforcing or something of that sort.
To find the source, go to the host server and try connecting the port
telnet 127.0.0.1 3000
Did you get 'Connection refused' error? if so which server is running the code? make sure firewall service is either off or with exceptions for port 3000. on linux check enforcing .
If the connection succeed, test the connection from your local pc
telnet ip_address 3000
If it fails than test access to external service (for example portquiz.net) This way you will know if the issue is with your local pc or network, or the remove server.

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.

Resources