How to socket.io emitting and receiving simple data? - node.js

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.

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 !

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 send a temporary chunk of html and js to a running app on node.js

I just got my first app up and running on Node.js. As of now, it is simply serving up a static file. But I have a few ideas that will be implemented down the road so I'm going ahead and getting Node setup so I'll be ready for it when that time comes.
// get modules
var express = require('express');
var fs = require('fs');
// create app instance
var app = express();
// static files middleware
app.use("/assets", express.static(__dirname + '/assets'));
// main route
app.get('/', function(req, res) {
var html = fs.readFileSync('assets/views/main.html', 'utf8');
res.send(html);
});
// make web server listen on specific port
app.listen(8080);
NOTE: I realize I don't need Express to serve one route, but I figured what's the harm in getting a head start on that as well?! :)
The first idea i had is to make a way to let all users currently using the app that there has been an update and that they must refresh their browser. There is no need to save the current state of the app as it is pretty basic.
So, if I am a user, I'm using the app and boom, I get a pretty little modal-window-alert-notification thingy letting me know that I need to refresh.
Also, if some user loads the app AFTER I have sent the alert, that user should not see the alert at all (because they should already be seeing the new changes).
I have done some googling on the subject and I'm just not satisfied with the examples i found. I do not think I want to have to update a notifications.xml file (which node.js would be watching) to push a new notification.
One solution I can think of would be to make a command that can be executed from the command line that will (somehow) send a new notification to the app. Perhaps using something like Grunt.js (I'm not sure if it would be a good fit for this as I've never used it). Basically, once the notification has been sent, all traces of it should disappear. That's why I think a command line approach would be good.
Here's my question: How (generally speaking) should I implement something like this? I am a Node.js newbie but I am pretty comfortable with javascript and the command line.
Please feel free to offer up any alternative solution you think would be better for me (other than a command line approach), or any tools that you think could help me.
Thanks!
If you want to push updates to a web client, one way is to use something like Socket.io. This creates a two-way pipe between client and server that you can use to asynchronously push updates through.
Sample server:
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Sample client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
alert('New news has come in! Please refresh your page!');
socket.emit('my other event', { my: 'data' });
});
</script>
The other option is to poll from the client using Javascript to actively look for updates. You would need to keep some state on the server for each client that would determine if that client required an update. The client would then make a get request on some timer interval (once a second, for example) to a secondary route and the server would reply with 'Yes, you need an update' or 'No, you don't need an update'. If yes, the client Javascript would then pop up your modal box and tell the user to refresh.

How to use a dynamic port # with socket.io and node.js?

When I use socket.io with node.js server, I usually use the following code (from the socket.io official site).
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3023');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
as you see, I'm hard coding my server ip with port number. Is there a way to set a variable in node.js server then use the variable on my client side code?
For now, I'm using cookie.
There are two basic options actually. If your socket.io client runs on the same address as your page, use:
io.connect(document.location.href);
Or, you can use a template engine to inject data from the server to the client page.
In recent versions of Socket.IO, you can just call io.connect() and it will auto-discover the URL.

Resources