Networking websockets on node.js servers - node.js

So I've been coding in web design for two weeks now and I've devolved the core for my io game on node.js just by using localhost:3000 now I'm trying to implement what I have so far into an actual web-server. It's one heck of a learning curve, so say I set up a virtual-machine in Google Cloud Platforms running node.js, socket.io what do I even set my ports too?
This is my Code currently server side:
var express = require('express'); //adds express library
var app = express();
var server = app.listen(3000); //listens on port 3000
app.use(express.static('public')); //sends the public(client data)
console.log("Server Has Started");
var socket = require('socket.io'); //starts socket
var io = socket(server);
This is my Code currently client side:
var socket = io.connect("http://localhost:3000")
my website is gowar.io and it currently resides as a static file in googles "bucket". How do I hook up my websockets with something like a virtual machine?

Typically, cloud ecosystems will give you an endpoint for your storage or allow you to configure one.
Skim through Google's Docs about WebSockets to learn more about their recommended implementation of WebSockets.

Related

How to run a gRPC Server and an Express Server on the Same PORT in cloud run

Are there any known techniques or hacks for running both an Express Server and a GRPC Server on the same port? I am aware Cloud Run exposes just a single Port for a service instance.
So, I'm literally just looking for hacks as it stands now.
Like below
const app = express();
const port=process.env.PORT;
app.listen(port,()=>{});
gRPCServer.bindAsync(`0.0.0.0:${port}`, grpc.ServerCredentials.createInsecure(), () => {
gRPCServer.start();
});
I wish to expose some routes to my users via express and only use GRPC for internal micro services communication.
I saw https://github.com/grpc-ecosystem/grpc-gateway but there are very few documentations on how to use it with NodeJS plus I DON'T want to generate client libraries. I prefer dynamic code generation.

NodeJs - express and socket.io same port integration

I am creating a server using NodeJs and Express, but I found out that if I want to make a service live, I need to use Socket.io. In this server, there are some service that don't need to be live, and these are implemented using express routes. This are tested and correctly working. Now I have to let some services to be live. So, I think I should implement also socket.io in my server configuration. This is my code without socket.io, working perfectly:
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.port || 5050;
app.use(morgan('dev'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended:true }));
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser:true});
const connection = mongoose.connection;
connection.once('open', () => console.log('Connected'));
const routes = require(#every routes);
app.use(routes);//all created routes
app.listen(port, () => {console.log(`Server listening on port ${port}`)});
NOw, I should import correctly socket.io. When it is done, I think I can figure out correctly hot to implement my services. So, I tryied to add the line const io = require('socket.io').listend(app) as I saw in another stackoverflow quesion, but the terminal shows up this error:
const io = require('socket.io').listend(app)
^
TypeError: require(...).listend is not a function
So, I don't know how to integrate this two. I don't know if it is worth to use the same port, or if I should use another port for the socket, but I think the same port would be good. If someone knows how to implement socket.io in my current code, or a way to keep both functionalities, please help me. Thank you so much
Change this:
app.listen(port, () => {console.log(`Server listening on port ${port}`)});
to this:
const httpServer = app.listen(port, () => {console.log(`Server listening on port ${port}`)});
Then, add this:
const { Server } = require("socket.io");
const io = new Server(httpServer );
This will let both your Express server and your socket.io server share the same http server. Since all incoming socket.io connections are identifiable with some custom headers, the socket.io code (actually the underlying webSocket transport does this) can grab those and handle them independently from your regular http requests.
See plenty of examples in the socket.io doc which has improved immensely from its early days.
Sometimes, it's easy to get confused looking at different examples because there are a dozen different ways to create your http server that you use with Express. The general idea here is that whichever way you use, just make sure you assign the http server instance that you created to a variable that you can then use with socket.io server initialization (as shown above). In your Express code, app is not the server. That's the Express app object which is also an http request handler. It's not the server. The server is something you get from http.createServer() or something that app.listen() returns to you (after calling http.createServer() internally).

Between Node.JS and Express, can someone explain where the Web Server fits in?

I've recently started server-side development using Node JS and Express but i'm getting confused as to how it all works. From my understanding, The web serve stores the website and returns the pages as they're requested from the browser. Apache is a web server and you would use that for a stack like XAMPP. ASP.NET is a framework that uses IIS Web Server and communicates with that.
But with Node, where's the server? Node is runtime environment and is USED to CREATE a server and Express is a web FRAMEWORK to help with server http requests but what/where is the actual web SERVER? Maybe i'm just not understanding web servers or something? Someone please clarify!
For Node, we do not need a web server like Apache or a container that sort of, node can listen to a port and act as a server itself,
and express is web application framework for Node which provides set of features to make life easier.
for a vague comparison, if Node is a telephone then Node + express will be a smartphone. - both can do same stuff but latter have more convenient features.
see below two example of creating a server which listen to a port 3000,
In node:
const http = require('http')
const requestHandler = (request, response) => {
console.log(request.url)
response.end('Hello Node.js Server!')
}
const server = http.createServer(requestHandler)
server.listen(3000,() => console.log("app started"));
Node + express
const express = require('express');
const app = express();
app.get('/', function (req, res) {
res.send('Hello express !')
})
app.listen(3000,() => console.log("app started"));
Both does the same thing, but with express things are easier.

Need for http.createServer(app) in node.js / express

Using node and express, the below works just fine.
var app = express();
app.listen(app.get('port'), function() {
});
I assume that a server is created implicitly in the above construct.
When adding socket.io, I've seen the following being done.
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.listen(app.get('port'), function() {
});
What is the need for explicitly adding http.createServer(app) ? Won't the creation of an additional server mess up things ? Or put it other way, is it ok to create many more http.createServer(app) ?
In either case, only one server is created. When using socket.io, you share the same http server between socket.io and express. Both libraries attach event listeners to the same server and have a chance to respond to the same events. They cooperate nicely because socket.io only handles relevant requests and express handles all the non-websocket requests. And just FYI you could not create more than one server on the same port. Only one process can listen on a TCP port at a time in the OS, so the second one would fail with an error when attempting to bind an in-use port.

Node.js hosting with Socket.io client support?

I made a socket.io client app which connects to my socket.io server and then they communicate whatever they need to.
When I do it locally on one machine or even on two different local machines, everything works fine. So I tried to deploy the client on cloud9 and it keeps throwing this error:
net.js:540
connectReq = self._handle.connect(address, port);
Error: No local connects allowed for security purposes
at connect (net.js:540:31)
at net.js:607:9
at Array.0 (dns.js:88:18)
at EventEmitter._tickCallback (node.js:190:38)
The client code is, where [ip-address] is my servers IP address:
var io = require('socket.io-client'),
socket = io.connect('[ip-address]', {
port: 1337
});
Is there a way to run such a socket.io client at c9.io?
Did they block it because of this article?
Are there any free node.js hosting solutions where one could run a socket.io client application like the one above?
Thanks.
Depending on your needs you could create a free Heroku account. You wont have access to a database, and you're limited in resources, but if the app is small enough and efficient enough it could suffice.
Nodejitsu is currently free node.js hosting solution where everything works (including socket.io)
OpenShift uses Port 8080 and Heroku 3000.
The Client code has to be like this:
// Wrong!:
// mySocket = io.connect(host, port);
// Right:
mySocket = io();
mySocket.on(....);
The Server code has to look like this:
var express = require('express'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server);
app.use(express.static('path/to/public/html'));
server.listen(8080); // OpenShift 8080, Heroku 3000
io.on(...);
https://devcenter.heroku.com/articles/node-websockets#create-a-socket-io-client

Resources