Socket io namespaces do not fire on("connection") event - javascript

I am using socket.io both (server API and client API) on Node.js as client and server. This is possible as specified in the docs). I am not using any particular frameworks except Express and followed the official guide for using socket.io with it.
On the server side I have:
const express = require("express");
const app = express();
const http = require("http");
server = http.Server(app);
const io = require("socket.io")(server) //server listens on "http://localhost:3001
io.on("connection", socket => {
console.log("server says: someone connected");
});
On the client side I have:
const io = require("socket.io-client")("http://localhost:3001");
io.on("connect", () => {
console.log("client says: connected");
});
Until here everything works fine... Now when adding namespaces nothing seem to work anylonger. I followed the official guide and ended up with the following:
On the server side I have:
const express = require("express");
const app = express();
const http = require("http");
server = http.Server(app);
const io = require("socket.io")(server) //server listens on "http://localhost:3001
const nsp = io.of('/my-namespace');
nsp.on("connection", socket => {
console.log("server says: someone connected");
});
On the client side I have:
const io = require("socket.io-client")("http://localhost:3001");
const socket = io('/my-namespace');
socket.on("connect", () => {
console.log("client says: connected");
});
But the after the introduction of namespaces nothing seems to work... What am I missing?!
Thanks I am completely lost

Related

Problems with Webhooks and Websockets on the same port

I have a server that receives webhooks, sends them to a client via websockets. Since I am listening for both on the same port, if webhooks work, websockets dont and vice versa. How would I go about solving this. Here is the code for the server
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json())
app.post("/", (req, res) => {
console.log(req.body);
res.status(200);
res.send(req.body);
echo(req.body);
});
app.listen(3000, '0.0.0.0', () => console.log('Server is live at 3000'));
const WebSocket = require('ws');
const SocketServer = require('ws').Server;
const server = express().listen(3000);
const wss = new SocketServer({server});
wss.on('connection', (ws) =>{
console.log("Connected");
ws.send("Connected To Server")
ws.on('close', () => console.log("Disconnected"));
});
function echo(webhook){
wss.clients.forEach(function each(client){
client.send(webhook);
});
}
How would I run webhook listener and websocket sender/listener on same port
Can I run both of them on different ports on the same url
a) If yes what would be the url for both ports, if my website is www.example.com
If all that is not possible, what would be a good alternative

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.

Why am I not able to access the express server from a different file?

I have set up an express server as follows (inside of server.js ) :
const app = express();
.........
.....
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Server started on port ${PORT}`)
);
module.exports = server;
Inside of another file socket.js:
const server = require("./server");
const socketio = require("socket.io");
const io = socketio(server);
io.on("connection", function (socket) {
console.log("A user just joined!");
socket.on("disconnect", () => {
console.log("A socket just left!");
});
});
For some reason I get an error in my console while trying to connect to the socketio on the client:
GET http://localhost:3000/socket.io/?EIO=3&transport=polling&t=N8-d7Q4 404 (Not Found)
The error does not occur if I execute everything in a single file (without exporting the server):
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () =>
console.log(`Server started on port ${PORT}`)
);
const socketio = require("socket.io");
const io = socketio(server);
io.on("connection", function (socket) {
console.log("A user just joined!");
socket.on("disconnect", () => {
console.log("A socket just left!");
});
});
I don't understand what's wrong. Does module.exports not work with the express server or is this is a socketio issue ?
It appears you're not loading socket.js at all. When you had only the one file, you just did node app.js and that would work fine. But, if you do node app.js with your two files, then there's nothing to ever load socket.js at all. In fact, the way you have the two files laid out, you would have to do:
node socket.js
to initialize things. Then, socket.js does a require('./app.js') to get app.js loaded.
I was wondering if it's impossible to module.exports = server at all
Yes, you can freely export the server and you are exporting it.
Another way of doing things is to still have app.js be your main file that you load to start up your app and you load socket.js from there and pass it the server object so it can use it.
// app.js
const server = const server = app.listen(...);
// load socket.js and pass it our server
require('./socket.js')(server);
Then in socket.js:
// socket.js
const socketio = require("socket.io");
module.exports = function(server) {
const io = socketio(server);
// rest of your module code here
}

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.

Socket.IO Client How to Connect?

I was following the second example here:
https://github.com/socketio/socket.io-client
and trying to connect to a website that uses websockets, using socket.io-client.js in node.
My code is as follows:
var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket');
socket.on('connect', function() {
console.log("Successfully connected!");
});
Unfortunately, nothing gets logged.
I also tried:
var socket = require('socket.io-client')('http://website.com/');
socket.on('connect', function() {
console.log("Successfully connected!");
});
but nothing.
Please tell me what I'm doing wrong. Thank you!
Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.
Socket.io Client
const io = require('socket.io-client');
const socket = io.connect('http://website.com');
socket.on('connect', () => {
console.log('Successfully connected!');
});
Socket.io Server w/ Express
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 1337;
server.listen(port, () => {
console.log(`Listening on ${port}`);
});
io.on('connection', (socket) => {
// add handlers for socket events
});
Edit
Added Socket.io server code example.

Categories