Why heroku can't run WebSocket server without HTTP server? - javascript

I have a WebSocket app on heroku. I tried uploading my WebSocket app without routing http server but it doesn't work. What does mean server routing? And why can't heroku run a WebSocket server without an http server?
And why does it takes express object 'server' as argument in SocketServer
Here's my code of Websocket server.
const express = require('express');
const SocketServer = require('ws').Server;
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const wss = new SocketServer({ server });
wss.on("connection",function(ws){
ws.on("message",function(message){
if(message==='exit'){
ws.close();
}else{
wss.clients.forEach(function(client){
client.send(message);
});
console.log(message);
}
});
ws.send("welcome..");
});

There are too many questions in one. I hope my answers will address all of them.
First of all, the websocket protocol is an extension of http, it is not something different. Therefore, a websocket server is necessarily an http server, even though with extended capabilities.
Also, with socket.io, the websockets and http run on the same port. Therefore you have to open the port for http to have your websockets work.
Let's have a look at this line :
const wss = new SocketServer({ server });
It has a syntax error, it must be new SocketServer(server). Also, about the variable name, I would recommend not to use wss for a websocket over http, since wss stands for secure websockets and is related to websockets like http to https.
About routing in heroku: in heroku, you have to define which port your application is using. This can be compared to the firewall on your local machine : if you want to access it from outside, you have to open the port. On heroku, technically it is different to a firewall, but in this point it is similar.

Related

How to keep socket.io client in frontend code

I am just learning webdev and want to try to make a multiplayer game using Express and socket.io
I can make a server with socket.io in it which listens. That part works fine.
However when I try to connect a client, this only works if I let the HTML file with the following in it be served by the server like follows:
Server code:
const express = require('express')
const app = express()
const http = require('http')
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server)
const port = 3000
io.on('connection', (sock) => {
console.log('client connected')
})
// This seems to be necessary, but I don't want it to be!!!
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
server.listen(port, () => {
console.log(`Server listening on port ${port}`)
})
This index.html has the following at the bottom:
<script src="/socket.io/socket.io.js"></script>
<script>const socket = io()</script>
However I want to keep all my frontend code seperate from the server. I made a seperate repository for the frontend and backend. I want the frontend to contain all the UI logic and use only data calls (AJAX) to get Json data from the server. So I want to put this index.html file in my frontend code only.
Yet if I do this the connection doesn't work.
I can start the server fine.
I open index.html from WebStorm which also creates a server for this which I configured to also listen to port 3000
Yet it cannot find /socket.io/socket.io.js and I get the following error in the console.
It also doesn't work if WebStorm runs on a different port.
The resource from “http://localhost:3000/socket.io/socket.io.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
How can I keep this html in my client repo only and still work with socket.io, or is this not possible?
You can't have multiple servers listening on the same port. Run the servers on different ports and either:
Have a reverse proxy forwarding requests to your Socket.io server (which needs special handling) and your front end server or
Put an absolute URL in the script src and configure CORS.

Failed to load resource: the server responded with a status of 404 (Not Found) Node.js socket.io

I'm trying to create a server using Node.js and socket.io and it starts perfectly. However, when I'm trying to visit the site of my server through the browser, he writes "Cannot Get /" and in the console gives an error "Failed to Load Resource: The Server Respondd with A Status of 404 (Not Found)". For two days I'm trying to understand where the problem and I will be very grateful to your help. Here is my server code:
const express = require("express");
var http = require("http");
const app = express();
const port = process.env.PORT || 5000;
var server = http.createServer(app);
var io = require("socket.io").listen(server);
//middlewre
app.use(express.json());
io.on("connection", (socket) => {
console.log("connected");
console.log(socket.id, "has joined");
socket.on("/test", (msg) => {
console.log(msg);
})
});
server.listen(port, "0.0.0.0", () => {
console.log("server started");
});
Your server is currently not set up to handle any other http traffic than Websocket connection upgrade requests, which you can not make by entering a url in your browser. Also, the browser is not equipped to negotiate this connection upgrade or to keep the Websocket connection working once established. For this you need some javascript code to run on the client side.
The socket.io library provides everything you need, look at a minimally working example at the link provided below. You should basically just set up your server to serve an html document which provides a context from which the whole websocket connection upgrade can be managed - and the connection maintained - by the socket.io library.
https://socket.io/docs/v2#Minimal-working-example

"Where" are Websocket servers hosted on Heroku?

I'm trying to host a Websocket server on my heroku app. There already is a GraphQL server running, but I don't think it's the cause of my problem.
So my server is started like this
const wss = new ws.Server({ port: port }, () => console.log(`Serveur WebSocket prêt ${port}`));
There is no error, but when I try to connect to the server in my browser, just like this :
const ws = new WebSocket('wss://ethyme-api.herokuapp.com/');
I get an error 404.
So my question is, what is the path of the ws server, so I can connect to it ?
Thanks
If your Heroku app is called ethyme-api and and your locally run application is available under ws://localhost:$PORT/ the websocket will be available under wss://ethyme-api.herokuapp.com/ and ws://ethyme-api.herokuapp.com/

Node.js + Apache - https://localhost:3000/socket.io/ ERR_CONNECTION_REFUSED

I am implementing a simple game in Node.js. I have a client.js for my client side code, and a server.js running on a remote server, which both use sockets to communicate on port 3000
I am also running Apache on port 80, and using ProxyPass in my apache configuration file, to route the url mywebsite.io/agario to my nodejs server.
<Location /agario>
ProxyPass http://localhost:3000/
ProxyPassReverse http://localhost:3000/
</Location>
I am also using cloudflare to route my webserver 167.179.xx.xx through the url https://agario.mywebsite.io for SSL so that I can use HTTPS.
The problem
When I try to connect to my website https://agario.mywebsite.io/agario I am receiving the following error:
socket.io-1.4.5.js:1 GET https://localhost:3000/socket.io/?EIO=3&transport=polling&t=MakAMgZ net::ERR_CONNECTION_REFUSED
I am unclear why my client code is trying to connect to localhost, when I have specified in the code to connect to the remote server. Potentially I am just confused on how to run the node.js server as this is my first taste of Node.js and sockets.
client.js
...
var socket;
socket = io.connect('https://agario.mywebsite.io/agario');
...
server.js
var app = express();
var server = app.listen(3000, listen);
// This call back just tells us that the server has started
function listen() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://' + host + ':' + port);
}
app.use(express.static('public'));
var io = require('socket.io')(server);
io.sockets.on('connection',
function(socket) {
console.log("We have a new client: " + socket.id);
...
});
If I have missed out any vital information please let me know and I will update my question, thank you.
You server is listening on port 3000 and you're trying to connect with it via 443, you should try something like this
socket.connect('https://ip:3000');
However, if you're sure that ur client is using the same port as the server or u have a port forwarding then try to use netcat just to make sure the the problem is with your script not the network config :
nc -zv -w1 ip port

Node.js with express and websocket giving error during WebSocket handshake: Unexpected response code: 200

So I am trying to set up a website that also has websockets where both the http-server and the websocket listens on the same port:
const WebSocket = require('ws');
var express = require('express');
var app = express();
wss = new WebSocket.Server({server : app});
app.get('/', function(req, res){
res.send('hello world!');
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('some text');
});
app.listen(8080, function(){
console.log('app started');
});
If I then load the servers website in chrome-browser I am greeted with "hello world!". So far so good. But if I open up the webconsole and try to connect with
var exampleSocket = new WebSocket("ws://192.10.10.30:8080");
I get the following errormessage:
WebSocket connection to 'ws://192.10.10.30:8080/' failed: Error
during WebSocket handshake: Unexpected response code: 200
My first thought was, do I have to explicitly declare an http-server ?
But I read this post
Serve WebSocket and HTTP server at same address on Node.js and there was no http-server explicitly declared. Please help me on this.
You're passing an Express app instance as server, which should be an HTTP/HTTPS server instance. Such an instance is returned by app.listen:
var app = express();
var server = app.listen(8080, function(){
console.log('app started');
});
wss = new WebSocket.Server({server : server});
I was having this issue on a Windows machine and discovered the reason was IIS did not have the WebSocket Protocol turned on. Ensure IIS on the machine supports WebSocket:
Control Panel -> Programs and Features -> Turn Windows features on or off.
Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then ensure WebSocket Protocol is checked.

Categories

Resources