Why does my socket.io webapplication keeps loading, i've implemented auth with certifications, but when i try to access localhost, it keeps loading. ive tried follow this doc, but dosent help:https://socket.io/docs/v3/client-initialization/
i dont get any error.
server.s
'use strict';
// Setup basic express server
var express = require('express');
var app = express();
var port = process.env.PORT || 4000;
var crypto = require('crypto');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./data/db.sqlite');
const bcrypt = require('bcrypt');
const tls = require('tls');
var validator = require('validator');
// Routing
app.use(express.static(__dirname + '/public'));
app.use(express.json());
// Chatroom
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;
const fs = require("fs");
const server = require("https").createServer({
cert: fs.readFileSync("./server-cert.pem"),
key: fs.readFileSync("./server-key.pem")
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
const io = require("socket.io")(server);
io.on('connection', function (socket) {
console.log("works")
}
client.js
const fs = require("fs");
const socket = require("socket.io-client")(4000, {
ca: fs.readFileSync("./server-cert.pem")
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
Related
Need your help/guidance/suggestion for our scenario.
Issue: I am having some trouble connecting socket io client to socket io server. The error I got after running this code is connection time out.
My server code is :
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.Server(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ",port);
});
My client code is:
<script src = "socket.io.min.js"> </script>
<script>
var socket = io.connect(`wss://${document.location.hostname}:${port}`);
console.log(socket);
socket.on('done', (data) => {
console.log(data);
});
</script>
Your server code does not start in my node installation.
I correct your server code with this below and seems to work
fine on my node installation. You forgot to link express library
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const express = require('express');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.listen(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ", port);
});
You can do with this script. This is my personal working script for socket IO chat app.
Backend Server
require("dotenv").config();
const port = process.env.SOCKET_PORT || 3000;
const main_server_url = process.env.SERVER_URL;
var express = require("express");
var app = express();
var server = app.listen(port);
var connectionOptions = {
"force new connection": true,
"reconnection": true,
"reconnectionDelay": 2000, //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
"reconnectionDelayMax": 60000, //1 minute maximum delay between connections
"reconnectionAttempts": "Infinity", //to prevent dead clients, having the user to having to manually reconnect after a server restart.
"timeout": 10000, //before connect_error and connect_timeout are emitted.
"transports": ["websocket"] //forces the transport to be only websocket. Server needs to be setup as well/
}
var io = require("socket.io").listen(server, connectionOptions);
var axios = require("axios");
var users = [];
var connections = [];
console.log("Server connected done");
io.sockets.on("connection", function (socket) {
var server_url = main_server_url;
console.log(server_url);
console.log(people);
connections.push(socket);
console.log("Connected : total connections are " + connections.length);
// rest of events of socket
});
Front End JS for load IO for client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script type="text/javascript">
var base_url = YOUR_BASE_URL;
var port = YOUR_SOCKET_PORT;
var socket_port_url = base_url + ":" + port;
var socket = io(socket_port_url);
socket.on('done', (data) => {
console.log(data);
});
</script>
I'm new to WS and Heroku and all that... so i have this code
//this sets up client-side sockets i guess
import {io} from 'socket.io-client';
const options = {
"force new connection": true,
reconnectionAttempts: "Infinity",
timeout : 10000,
transports : ["websocket"]
}
const socket = io('/', options)
export default socket;
and for the server side
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const {version, validate} = require('uuid');
const ACTIONS = require('./src/socket/actions');
const PORT = process.env.PORT || 3001;
///more code
When deployed to heroku this results in this app https://lit-atoll-99067.herokuapp.com/ and the chrome console says :
WebSocket connection to
'wss://lit-atoll-99067.herokuapp.com/socket.io/?EIO=4&transport=websocket'
failed: WebSocket is closed before the connection is established.
So i ran out of ideas. but i guess this has to be about port or something... dunno really. Any ideas are welcome!
I think you need to pass the full URL at the client-side but you only passed the "/" only example:-
import {io} from 'socket.io-client';
const options = {
"force new connection": true,
reconnectionAttempts: "Infinity",
timeout : 10000,
transports : ["websocket"]
}
// here need to pass the full url
const socket = io('https://example.com/', options)
export default socket;
And for the server side try this
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);
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
I'm trying to get HTTPS working on express.js for node, and it won't run.
This is my server.js code.
const fs = require('fs');
const http = require ('http');
const https = require('https');
const options = {
pfx: fs.readFileSync('ssl/pfxfile.pfx'),
passphrase: 'password'
};
const express = require('express');
const app = express();
const path = require('path');
app.use(express.json());
app.use(express.static("express"));
app.use('/', function(req,res){
res.sendFile(path.join(__dirname+'/express/index.html'));
});
var httpServer = http.createServer(app);
var httpsServer = https.createServer(options, app);
httpServer.listen(8080);
httpsServer.listen(8443);
When I run it reports no errors but it just get stuck to nothing (I waited 30 minutes to see if it does something and nothing happened).
httpServer.listen(8080, ()=>{console.log('Server is running')});
If the server successfully started, it should output "Server is running" in the console. This is a nice way to check if the server is working as intended.
I found my error, thanks for your answers, it's been helping me, my error was first that I didn't put any console.log and the second was that I was not typing 8443 in the browser.
const fs = require('fs');
const http = require('http');
const https = require('https');
const options = {
pfx: fs.readFileSync('ssl/pfxfile.pfx'),
passphrase: 'password'
};
const express = require('express');
const app = express();
const path = require('path');
app.use(express.json());
app.use(express.static("express"));
app.use('/', function(req,res){
res.sendFile(path.join(__dirname+'/express/index.html'));
});
const httpServer = http.createServer(app);
const port = process.env.PORT || 8080;
const httpsServer = https.createServer(options, app);
const portHttps = process.env.PORT || 8443;
httpServer.listen(port, () => console.log('Http listening on port ' + port));
httpsServer.listen(portHttps, () => console.log('Https listening on port ' + portHttps));
I am trying to console.log a message whenever someone connects to my server. Please advise what I did wrong or how to improve my code.
server.js
// express server setup
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const server = require('http').createServer(app)
const io = require('socket.io')(server)
const port = process.env.PORT || 1991
// middleware
app.use(cors())
//api
const metrics = require('./routes/api/metrics')
app.use('/api/metrics', metrics)
//
server.listen(port, () => {
console.log(`server running # port ${port}`);
})
io.sockets.on('connection', function (socket) {
console.log('socket.io connected')
})
I'm trying to use two Node.js express servers on a Windows Server 2012, each one with a different FQDN (example1.b.br | exemple2.b.br).
The applications are two Watson Chatbots, so both of them need to use route /conversation to communicate with IBM.
One chatbot uses port 443 and the other one use 8443.
The problem is: Each one of them are in different directories and have their own subdirectory called 'public', but when I execute both servers, the one using port 8443 uses the port 443 server's 'public' subdirectory.
Chatbots
certificates
Chatbot1
node_modules
public
css
script
Chatbot2
node_modules
public
css
script
Chatbot1 app.js:
const AssistantV1 = require('watson-developer-cloud/assistant/v1');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const https = require('https');
var fs = require('fs');
var httpApp = express();
var workspace;
var options = {
key: fs.readFileSync('certificates/key.pem'),
cert: fs.readFileSync('certificates/server.crt')
};
const app = express();
app.use(bodyParser.json());
app.use(express.static('./public'));
const port = 80;
const httpsPort = 8443;
httpApp.set('port', process.env.PORT || 80);
const assistant = new AssistantV1({
username: 'XXXXX',
password: 'XXXXX',
url: 'https://gateway.watsonplatform.net/assistant/api/',
version: '2018-02-16'
});
workspace = 'XXXXXXX';
app.post('/conversation/', (req, res) => {
const { text, context = {} } = req.body;
const params = {
input: { text },
workspace_id: workspace,
context,
};
assistant.message(params, (err, response) => {
if (err) res.status(500).json(err);
res.json(response);
});
});
try{
//var httpServer = http.createServer(httpApp, app).listen(port);
var httpsServer = https.createServer(options, app).listen(httpsPort);
//httpServer.listen(port, () => console.log(`Running on port ${port}`));
httpsServer.listen(httpsPort, 'exemple1.b.br', () => console.log(`HTTPS Running on port ${httpsPort}`));
console.log(`---------------------------------`);
console.log(`-----------ROBO INICIADO---------`);
console.log(`---------------------------------`);
}catch(err){
console.log(`*********************************`);
console.log(`*****Falha ao iniciar o Robo*****`);
console.log(`*********************************`);
console.log(err);
} */
Chatbot2 app.js:
const AssistantV1 = require('watson-developer-cloud/assistant/v1');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const https = require('https');
var fs = require('fs');
var httpApp = express();
var workspace;
var options = {
key: fs.readFileSync('certificates/key.pem'),
cert: fs.readFileSync('certificates/server.crt')
};
const app = express();
app.use(bodyParser.json());
app.use(express.static('./public'));
const port = 80;
const httpsPort = 443;
httpApp.set('port', process.env.PORT || 80);
const assistant = new AssistantV1({
username: 'xxxxxxx',
password: 'xxxxxx',
url: 'https://gateway.watsonplatform.net/assistant/api/',
version: '2018-02-16'
});
workspace = 'XXXXXXX'
app.post('/conversation/', (req, res) => {
const { text, context = {} } = req.body;
const params = {
input: { text },
workspace_id: workspace,
context,
};
assistant.message(params, (err, response) => {
if (err) res.status(500).json(err);
res.json(response);
});
});
try{
var httpsServer = https.createServer(options, app).listen(httpsPort);
httpsServer.listen(httpsPort, 'exemple2.b.br', () => console.log(`HTTPS Running on port ${httpsPort}`));
console.log(`---------------------------------`);
console.log(`-----------ROBO INICIADO---------`);
console.log(`---------------------------------`);
}catch(err){
console.log(`*********************************`);
console.log(`*****Falha ao iniciar o Robo*****`);
console.log(`*********************************`);
}
How can I "force" the server to use its own subdirectory?
"Problem" solved.
Actually, it was my lack of study about how FQDN actually works and a little to blame on Anti-virus.
example2.b.br don't need the ":443" on its url, because the port is default for HTTPS.
But when I use example1.b.br, it needs ":8443" after (https://example1.b.br:8443).
At least this simple mistake make me learn about this detail.
After that, I discovered that the server anti-virus were blocking some files. After creating an exception on the port to communicate only through intranet, the problem got solved.