socket.io is not showing console.log message when connected - javascript

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')
})

Related

Why my socket.io video chat won't work on heroku?

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');
});

Node js with express and socket.io -can't fint socket.io.js

So basically what i am trying to do is build a chat app with a login system but for some reason i cant put it together and i am getting an error when i join to the room the chat.hbs can't find the socket.io.js file and also the main.js is getting a reference error with the const socket = io(); (the chat app works fine without the login system)
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not definedat main.js:11
This is the app.js file
const express = require("express");
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = "Bot";
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.use(cookieParser());
app.set('view engine', 'hbs');
//eldönti az útvonalat
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
This is the main.js
const chatForm = document.getElementById('chat-form');
const chatMessages = document.querySelector('.chat-messages');
const roomName = document.getElementById('room-name');
const userList = document.getElementById('users');
// Felhasználó név és szoba név URL-ből
const { username, room } = Qs.parse(location.search, {
ignoreQueryPrefix: true,
});
const socket = io();
// Csatlakozik chat szobába
socket.emit('joinRoom', { username, room });
// Lekérdezi a szobát felhasználókat
socket.on('roomUsers', ({ room, users }) => {
outputRoomName(room);
outputUsers(users);
});
And the chat.hbs
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
Well the problem was that I used:
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
instead of:
server.listen(5001, () => {
console.log("Server started on Port 5001");
})
Szia, you will need to wait for the DOM to load.
window.addEventListener('load', function () {
// Your code goes here
const socket = io();
socket.on("connect", () => {
// you can only emit once the connection is established.
socket.emit('joinRoom', { username, room });
});
})

Trying to run express node js as https server but it won't run

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));

Socket.io is not found in the client-side

This is my Server Side:
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const port = 3000 || process.env.PORT;
app.listen(port, () => {
console.log(`server running on port ${port}`);
});
io.on('connection', socket => {
console.log(socket);
});
This is my Client Side:
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
</script>
</body>
</html>
I re-installed all the modules correctly, but it did not help.
The problem is that you're creating two web servers, attaching socket.io to one of them, but only starting the other one.
Both of these lines of code create a new web server:
const server = http.createServer(app);
app.listen(port, ...);
But, only the second one actually gets started and that's NOT the one you bound socket.io to. So, the server you bound socket.io to is never started, therefore none of the client-side stuff that is supposed to talk to your socket.io server will work properlly.
To fix it, change your server code to this:
const path = require('path');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const port = 3000 || process.env.PORT;
const server = app.listen(port, () => {
console.log(`server running on port ${port}`);
});
const io = socketio(server);
io.on('connection', socket => {
console.log(socket);
});
Now, you will only be creating one web server, starting that server and binding socket.io to that one server.

How do I transfer this local server API to a web API to deploy my app in heroku?

I have these code for a Chat App and it is only working in Local Server
I have already tried the following. Calling io() without any path arguments.
// Client Side Code
socket = io();
socket.connect({ query: `username=${props.username}` })
The above didnt work. The app runs but does not show other user's messages.
// Client Side Code
socket = io('http://myherokuapp:3001', { query:
`username=${props.username}` }).connect();
Neither did the above code work. The app crashed on this one.
Here is my actual source code:
// Server Side Code
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
const http = require("http");
const cors = require("cors");
const io = require("socket.io");
const server = http.createServer(app);
const socketIo = io(server);
app.use(cors());
app.get('/messages', (req, res) => {
res.sendFile(path.resolve('./public/index.html'));
});
socketIo.on('connection', socket => {
const username = socket.handshake.query.username;
console.log(`${username} connected`);
socket.on('client:message', data => {
console.log(`${data.username}: ${data.message}`);
socket.broadcast.emit('server:message', data);
});
socket.on('disconnect', () => {
console.log(`${username} disconnected`);
});
});
server.listen(PORT, () => {
console.log(`🌎 ==> API server now on port ${PORT}!`);
});
// Client Side Code
socket = io('http://localhost:3001', { query:
`username=${props.username}` }).connect();
socket.on('server:message', message => {
addMessage(message);
});
socket.emit('client:message', messageObject);
addMessage(messageObject);
I expect the chat app to be working same as it does in localhost.

Categories