How to run socketIO server together with main server on nodejs - javascript

Currently, we have a main server that is being hosted on localhost:3000 but to run our socket.io function, we need to run it on the same server. However, we need to run it separately (npm start separately). Is there a way to run it together or on the same server without it crashing?

You cannot run socket.io in a separate process, but on the same port as some other web server in some other process. The OS will not allow that as only one process can have a listening server on a specific port. If they are in the same process, that's easy as pie as socket.io is built to share an http server in the same process (one listening server internally, traffic divided between the two uses). But, not from separate processes.
To do that, you'd have to use something like nginx on your port 3000 to proxy plain web requests to one server on some other port say 3001 and socket.io requests to another server on some other port say 3002. The client would only deal with port 3000 and nginx would direct the traffic to the right server on different ports.
I'm thinking that when you say "npm start separately", you must have some other problem you're trying to solve with that statement and we could probably help with a better way to solve that actual problem (if you disclosed what that actual requirement is) while keeping socket.io and the http server in the same process and thus no need for a proxy to divide the traffic between two separate servers.
For example, you could start up your web server with no socket.io server started and then you could tell your web server process to start up the socket.io server later. Or you could start both the web server and socket.io server in the same process at initialization time, but have a temporary server configuration that blocks incoming socket.io connections until some other requirement is met.
But, without understanding what the real requirement is, you're just lobbing us an XY problem where you describe your attempted solution rather than the actual problem that needs to be solved. When we explain that your attempted solution is the wrong way to go, we need to know what the real problem is to help further.

This is simple SocketIo Server Code.
It's not a client code.
You have to download SocketIO at npm.
const express = require('express');
const http = require('http');
const SocketIo = require('socket.io');
const app = express();
app.set('view engine', 'pug');
app.set('views', __dirname + '\\views');
app.use('/public', express.static(__dirname + '/public'));
app.get('/', (req, res) => res.render('home'));
const handleListen = () => console.log('Listening on http://localhost:3000');
const httpServer = http.createServer(app);
const wsServer = SocketIo(httpServer);
wsServer.on('connection', (socket) => {
console.log('someone joined!')
socket.on('join_room', (roomName) => {
socket.join(roomName);
socket.to(roomName).emit('welcome');
});
});
httpServer.listen(3000, handleListen);
For more Info visit official documentation.
https://socket.io/get-started/chat

Related

Moving ExpressJS API files onto Server

So I created an simple API using ExpressJS that connects to MongoDB to perform CRUD operations. Currently I am able to get the local host running by performing command "npm nodemon" in the source folder. And it worked by testing with postman I wonder how to implement it on the server. As server runs a linux system, also I have a line of code in my root file "server.js ":
const port = process.env.PORT || 5000;
I think the process.env.port needs need to be changed in order to make it work on the server?
In addition, I did look into aws CE2 server it is so complicated that I was immediately overwhelmed. I am hoping someone can recommend dummy like me a simple and very specific solution to have a server run my scripts in ExpressJS environment. Thank you
I'm assuming your question is "How to deploy express app to a server?"
You can read some advanced topics on http://expressjs.com/, which covers some best practices, and other useful stuff. But the things you want to look at now is Things to do in your environment / setup
The important part is:
Keep your express runing on port 5000
Run your app in cluster
Run your app behind a proxy server like Nginx.
You can check this nice guide (Step 3 and 4) on how to deploy your express app to a Linux server with PM2, Nginx.
So at the end, your express app will run on port 5000 (or whatever port you desire), and your Nginx will run on port 80, and nginx will forward any request to your express app.

Node.js client can't see data from Express server

I am setting up a Client/Server communication between my tablet and my PC. My Client cant get any data from the server, what am I doing wrong.
My PC is running a Node.js server (using Express) and my tablet runs a client written in Node.js (using Express). I can access the server via the browser and get the data, but not through the javascript code.
My SERVER code is:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('App requested a connection');
});
app.listen(3000, () => console.log('Listening on port 3000!'));
app.get("/boxes", function (req, res)
{
//res.send(req.params[0]);
res.send("All boxes are in the basement");
});
My CLIENT code is:
const express = require('express');
const app = express();
console.log("Client working ...");
app.get("http://127.0.0.1:3000/boxes", function (req, res)
{
console.log("inside...");
console.log(res);
});
The CLIENT should return "All boxes are in the basement" and I get this when I use a browser but it doesn't work if I run the client code. The only message I get from client is "Client working ...".
Does anybody know what I am doing wrong?
Cheers
Express is a library for setting up and configuring an http server for incoming requests. It does not make outgoing requests to other servers. So, your client code is not a client at all.
Several problems here:
127.0.0.1 refers to your local device so your client is referring to itself when it uses 127.0.0.1.
In your client app.get("http://127.0.0.1:3000/boxes") is not a request for data. That attempts to set up an Express route for incoming requests as if you were declaring a second server. But, it's not even done correctly because you would only use the path there.
For a client to make a request of some other server, you would need to use a library call that actually does http requests. For example, you could do something like this:
Code:
const rp = require('request-promise');
rp.get("http://ipaddressOfServer:3000/boxes").then(data => {
// have response here
}).catch(err => {
// error here
});
I chose to use the request-promise library, but there are multiple different ways to make an http request. You can also use http.get() (lower level), request() (from the request library) or axios() from the axios library, etc...
Note, the computer your server is on (assuming it's running a desktop OS) will also have to probably turn of it's local firewall (e.g. windows firewall) or set up a specific rule to allow incoming connections on port 3000. Without that, the incoming connection will be blocked (for security reasons).

Given a server on Node. js, How do I listen to the calls sent to the server from WebSocket?

When I run the server, I wanted to be able to listen to the messages coming in to the server. However, the program/server is only set up to receive the calls without any notice
server.js
var express = require("express"),
program = require("program"),
app = express.createServer();
app.use(express["static"](__dirname + "/../"));
app.listen(5000);
//app.server to clients
program.init({
oscPort: xxxx,
oscHost: "xxx.xxx.xxx"
socketPort: app
});
You should add socket server because HTTP and Socket it's different protocols. There is a bunch of WebSocket servers like ws, socket.io so you could pick the one which is most suitable in your case. Here is an example how to use Socket.io with Express.

What HTTP address can I send requests to from when hosting on Heroku? (client to server)

This sounds really dumb, but...
I have a Node.js Express server that used to be completely functioning on my localhost. I recently deployed it on Heroku and made some changes so my actual index.js listens to process.env.PORT instead of localhost. it listens to process.env.PORT fine through that, but I have a page rendered in React.js called app.js stored within a directory (./js/app.js) that makes HTTP requests when buttons are clicked.
However, whenever I try accessing process.env.PORT from within the app.js to make these requests, process is undefined, so everything falls apart. When working on it locally, I would just send the requests to http://localhost:3000/database, but now I have to change that since it's deployed on Heroku now.
How can I communicate between my client (app.js) and my server (index.js)?
I know this is something super simple and I've tried searching for it for the past couple of hours, but I just don't know how to phrase it.
Thank you!
Try to define your address and port in your app.js file as a heroku server address:
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port; // put your adress here :)
console.log('Example app listening at http://%s:%s', host, port);
});
I am there if you get another pb :)

Node.js socket.io.js not found or io not defined

I'm trying to run a node.js application on my freebsd server, but I can't get the socket.io library to work with it. I've tried including:
<script src="/socket.io/socket.io.js"></script>
Which gives a 404 error, and if i link directly to the file (i.e. where it is in my public_html folder) I get the io not defined error.
Thanks in advance
Try creating another node.js application that has this single line in it and then run it with node.js
var io = require('socket.io').listen(8000);
Then in your browser visit http://127.0.0.1:8000 and you should get the friendly "Welcome to socket.io." greeting. If you are getting this then socket.io is running and will serve the socket.io.js file.
The only other thing that I can think of that might be happening is that you might not be linking to the alternate port in your client file. Unless you're running the socket.io server on express which is running on port 80. For now create a client file that has the script source for socket.io set to
<script src="http://127.0.0.1:8000/socket.io/socket.io.js"> </script>
This should connect to the socket.io server running on port 8000 and get the socket.io.js file.
Your node.js application still has to serve it - it does not get served automagically. What do you have in your server? It should be something like
var app = require('express').createServer();
var io = require('socket.io').listen(app);
or similar (the listen is important). The location is not a real location on the disk - socket.io library should intercept the URL and serve its clientside library, as far as I understand.
Add the following after body parser:
, express.static(__dirname + "/public")
So something like:
var app = module.exports = express.createServer(
express.bodyParser()
, express.static(__dirname + "/public")
);
For those who got the same kind of issue if they run (open) your html file directly from your local file directory(ex: file:///C:/Users/index.html).
Solution: You have to run(open) the file through localhost (ex: http://localhost:3000/index.html) where the server is listening to.
Below code snippet shows how to create a server and how to wire together with the express and socket.io
const express = require("express");
const app = express();
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);
///////////////////////////////////////////////////////////////
// Any other server-side code goes here //
//////////////////////////////////////////////////////////////
httpServer.listen(3000, () => {
console.log(`Server listening to port 3000`);
});

Categories