I would like to know if it's possible to create multiple socket servers on differents url routes on only one nodejs server.
I'm trying to have two differents server instance running on differents url
like mysite/instanceA and mysite/instanceB
When i tried to do that with port and not url. The application start well and on the port 3000 and 3001, i got two distincts application. It's great.
let express = require('express');
let http = require('http');
let socket = require('socket.io');
let workspace = require('./src/workspace');
class Server {
constructor(port){
this.httpServer = http.Server(app);
this.io = socket(this.httpServer);
workspace.newWorkspace(this.io , app);
this.httpServer.listen(port, function(){
console.log('App started on : ' + port);
});
}
}
let app = express();
app.use(express.static("public"));
new Server(3000);
new Server(3001);
But, i want do that with url and not port, so i tried something like that. I know why is not worked but i didn't know how to realize my aim.
Example:
let express = require('express');
let http = require('http');
let socket = require('socket.io');
let workspace = require('./src/workspace');
const port = process.env.PORT || 3000 ;
class Server {
constructor(){
this.httpServer = http.Server(app);
this.io = socket(this.httpServer);
workspace.newWorkspace(this.io , app);
this.httpServer.listen(port, function(){
console.log('App started on : ' + port);
});
}
}
let app = express();
app.use(express.static("public"));
app.get("/", function(req, res){
new Server();
});
app.get("/a", function(req, res){
new Server();
});
Related
I am writing this server app (express and socket.io), just at the beginning.
I see double log, so I have double connection to server when starting a tab at localhost:8080.
What am I doing wrong? Is this a Socket.io bug?
const express = require("express");
const path = require("path");
const socket = require("socket.io");
const port = process.env.PORT || 8080;
const app = express();
const server = app.listen(port);
app.use(express.static(__dirname + "/dist"));
app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname + "/dist", "index.html"));
});
// Socket setup
const io = socket(server);
io.on("connect", function (socket) {
console.log("Made socket connection");
});
The problem was that more js client files were calling socket().
Right method is to import socket.io library in , into your html file, so that this will be available to all js client file, implementing only one connection.
I have below application successfully started but it doesn't listen on port 8080.
var app = require('../app');
var debug = require('debug')('shanadminpanel:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
When I enter url localhost:8080, nothing happened.
You have use http
So you can create server by any of this .
Two way you can create server
by http module
var http = require("http");
var server = http.createServer(function(request, response) {
console.log("server created")
}).listen(80);
And by express you can do this.
by express
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I'm having trouble trying to figure out why I'm getting this 404 error. I've gone through all the other questions on this site that cover 'express-ws' and i've modeled my code exactly how the solutions prescribed yet the websocket won't make a connection. I'm trying to create a websocket connection between my express server and react app. Below are previews of my code:
Express using express-ws (server.js):
var express = require('express');
var expressWs = require('express-ws');
var bodyParser = require('body-parser');
var cors = require('cors');
var nodemailer = require('nodemailer');
var email = require('./credentials');
var port = process.env.PORT || 3001;
var path = require('path');
// const WebSocket = require('ws');
// const http = require('http');
expressWs = expressWs(express());
let app = expressWs.app;
var server = require('http').createServer(app);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('app/build'));
}
app.get('/', function(req, res){
console.log('server running!');
res.end();
});
app.ws('/ws', function(ws, req) {
console.log( 'socket running!' );
});
server.listen(port);
console.log('server started on port ' + port);
The GET route works fine but the ws route doesn't.
Call to express from React app:
componentDidMount() {
let ws = new WebSocket('ws://localhost:3001/ws');
ws.on( 'open', function open() {
console.log('app connected to websocket!');
} );
ws.on( 'message', function ( message ) {
console.log( message );
})
}
I've looked at all the following questions and don't understand why their solutions don't work for me:
Socket.IO 404 Error
express-ws connection problem
Node not working with express-ws
If anyone can let me know what's going on that would be great.
It seems your code does not follow express-ws's document. To use express-ws and make WebSocket endpoint, the code would be as:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
...
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
console.log('socket running');
});
app.listen(3000);
In the client side, ws object does not have field on. To listen WebSocket connection and message, you can use onopen and onmessage:
ws.onopen = function() {
console.log('app connected to websocket!');
};
ws.onmessage = function(message) {
console.log( message );
};
I had this exact problem and for me the solution was to change:
server.listen(port);
to:
app.listen(port);
I suspect what is going on is that express-ws is using the app listen function as its cue to start upgrading connections to ws and this won't happen if the server listen port occurs instead.
I am working in c9.io ide environment, I have written below code in server.js file
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var express = require('express');
var app = express();
var router = express();
var server = http.createServer(router);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/client'));
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.render('index.html');
});
app.get('/about', function (req, res) {
res.send('about');
});
After running node server.js in terminal the message given as
Your code is running at https://nodejs2-mujaffar.c9.io.
Important: use process.env.PORT as the port and process.env.IP as the host in your scripts!
Server listening at 0.0.0.0:8080
But after accessing https://nodejs2-mujaffar.c9.io/ url -- It is not rendering view only displaying message Error: Cannot GET /
What I am doing wrong?
Please help.
You seem to have created two instances of express which may be your problem.
Try changing:
var express = require('express');
var app = express();
var router = express();
var server = http.createServer(router);
to:
var express = require('express');
var app = express();
var server = http.createServer(app);
At the minute, your express app variable is not bound to your http server. You have instead bounded an unused instance called router. But then you have registered your routes to the app variable.
I'm trying to get a nodejs wss-server up and running. For this I'm using the Express4 Framework and the eniaros/ws module.
But sadly I'm not able to get the WSS-Server up and running. The normal WS-Server is working quite fine, but every time I try to connect to my WSS the client gets connected and directly disconnected again.
My certs are self-signed.
My code is shown below. It would be awesome if some one could please help me!
var express = require('express');
var router = express.Router();
var app = express();
var http = require('http');
var https = require('https');
var WebSocket = require('ws').Server;
var path = require('path');
var fs = require('fs');
// Routes
app.use('/', require('./routes/index'));
// Load config files
var db_conf = require('./config/vops_db_config.json');
var server_conf = require('./config/vops_server_config.json');
// TLS-Files
var cert_basepath = './config/certs/';
var tls_key = fs.readFileSync(cert_basepath + server_conf.tls.key_path);
var tls_cert = fs.readFileSync(cert_basepath + server_conf.tls.cert_path);
var https_options = {
ssl: true,
port: 3030,
key : tls_key,
cert: tls_cert
};
// Start all HTTP-Servers
var httpServer = http.createServer(app);
var httpsServer = https.createServer(https_options, app);
httpServer.listen(3000, function () {
console.log('HTTP-Server now listening on port ' + 3000);
});
httpsServer.listen(3030, function(){
console.log('HTTPS-Server now listening on port '+ 3030);
});
// Start WebSocket-Server
var wss = new WebSocket( { server: httpServer });
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send('something');
});