Let's say the entry point of my app is app.js
I want to create a socket connect when the app runs and then export it to other files throughout the application.
Here is a bit of example code
const express = require('express');
const WebSocket = require('ws');
const app = express();
app.use(allTheMiddleWares);
app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: app});
module.exports = socket;
Then when I try to access the export from app.js I always end up with an empty object.
I have also tried exporting functions:
module.exports = {
test: () => console.log("why don't I work")
}
However this also returns an empty object.
Thanks in advance for the help.
As a temporary work around to access the socket globally I have set process.WebSocket = new WebSocket.Server({server: app});. I would like to know if there are any glaring issues with this.
Making my comment into an answer since it was your solution.
You are not passing a server to the WebSocket constructor. app is a request handler. It is not a server. app.listen() returns a newly created server object.
Change your code from this:
app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: app});
to this:
const server = app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: server});
See code for app.listen() here.
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
See doc for app.listen() here.
The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:
Related
I am trying to make a simple server with socket.io and express and connect to it through a website.
when i followed a tutorial on socketio with localhost, everything worked fine, but when i put the server on a vserver, and tried to connect to it, i got this error:
Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR
as well as:
GET https://54.53.0.254:47185/socket.io/?EIO=4&transport=polling&t=O09jjrs net::ERR_SSL_PROTOCOL_ERROR
here is my server code:
const express = require('express');
const app = express();
const server = app.listen(47185);
const socket = require('socket.io');
const io = socket(server)
console.log('server running on port 47185');
io.sockets.on('connection', newConnection);
function newConnection(socket) {
console.log('new connection: ' + socket.id);
socket.on('input', inputLog)
function inputLog(data) {
socket.broadcast.emit('input', data);
console.log(data);
}
}
and here is my client code (this is all that relates to socket.io, the rest is just for the website)
var options = {
rejectUnauthorized:false
}
var socket;
socket = io.connect('89.58.0.199:47185', options);
socket.on('input', foreignInput)
function foreignInput(data) {
terminal_animate('\n' + data)
}
i have tried many different fixes and googled everything i can think of, and i'm just not sure what the problem is.
can anyone help me out with this issue? thanks in advance.
In the documentation, according to the Client Initialization part, in node.js you should provide the protocol when connecting to the server.
// the following forms are similar
const socket = io("https://server-domain.com");
const socket = io("wss://server-domain.com");
const socket = io("server-domain.com"); // only in the browser when the page is served over https (will not work in Node.js)
The first two example shows the secure https/wss as protocol, for that you need to serve the required files from the server, example in the documentation.
With http/ws as protocol it should work, but the communication will not be secure.
The Server Initialization / With Express shows an example to call .listen on the return value of createServer from the http module, with the app given as a parameter.
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, { /* options */ });
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
With a caution that says:
Using app.listen(3000) will not work here, as it creates a new HTTP server.
good afternoon. I am new to programming sockets in node.js and I need to implement socket.io in a controller of my application. The architecture I have is the following:
The file that starts the server is index.js
const express = require('express');
const app = express();
const port = 3000;
const socketRouter = require('./routes/socket')
app.use(express.json());
//Route
app.use('/socket', socketRouter);
app.listen(port, () => {
console.log(`Server connection on http://127.0.0.1:${port}`); // Server Connnected
});
The file where I define the routes is socket.js
const { Router } = require('express');
const { showData } = require('../controllers/socket');
const router = Router();
router.post('/send-notification', showData);
module.exports = router;
And my controller is:
const { response } = require('express');
const showData = (req, res = response) => {
const notify = { data: req.body };
//socket.emit('notification', notify); // Updates Live Notification
res.send(notify);
}
module.exports={
showData
}
I need to implement socket.io in this controller to be able to emit from it but I can't get it to work. Could you tell me how to do it?
Thanks a lot
CLARIFICATION: if I implement socket.io in the main file it works, but I want to have some order and separate things. This is how it works:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/send-notification', (req, res) => {
const notify = { data: req.body };
socket.emit('notification', notify); // Updates Live Notification
res.send(notify);
});
const server = app.listen(port, () => {
console.log(`Server connection on http://127.0.0.1:${port}`); // Server Connnected
});
const socket = require('socket.io')(server);
socket.on('connection', socket => {
console.log('Socket: client connected');
});
Move your socket.io code to its own module where you can export a method that shares the socket.io server instance:
// local socketio.js module
const socketio = require('socket.io');
let io;
modules.exports = {
init: function(server) {
io = socketio(server);
return io;
},
getIO: function() {
if (!io) {
throw new Error("Can't get io instance before calling .init()");
}
return io;
}
}
Then, initialize the socketio.js module in your main app file:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
const server = app.listen(port, () => {
console.log(`Server connection on http://127.0.0.1:${port}`); // Server Connnected
});
// initialize your local socket.io module
const sio = require('./socketio.js');
sio.init(server);
// now load socket.io dependent routes
// only after .init() has been called on socket.io module
const socketRouter = require('./routes/socket')
app.use('/socket', socketRouter);
Then, anywhere you want to access the socket.io server instance, you can
require("./socketio.js") and use the .getIO() method to get the socket.io instance:
// use correct path to socketio.js depending upon where this module
// is located in the file system
const io = require("../../socketio.js").getIO();
// some Express route in a controller
const showData = (req, res) => {
const notify = { data: req.body };
// send notification to all connected clients
io.emit('notification', notify);
res.send(notify);
};
module.exports= {
showData
};
Note: A typical socket.io usage convention on the server is to use io as the server instance and socket as an individual client connection socket instance. Please don't try to use socket for both. This makes it clear that io.emit(...) is attempting to send to all connected clients and socket.emit() is attempting to send to a single connected client.
Also note that if your route is triggered by a form post where the browser itself sends the form post, then that particular client will not receive the results of io.emit(...) done from that form post route because that browser will be in the process of loading a new web page based on the response of the form post and will be destroying its current socket.io connection. If the form post is done entirely via Javascript using an Ajax call, then that webpage will stay active and will receive the results of the io.emit(...).
You can use the same socket and app (if you need to expose APIs as well) in other files if you want to separate socket messages and REST endpoints by functionality or however you choose to organize it. Here's an example of how this can be done:
Create a new file, let's say controller1.js:
function initialize(socket, app) {
socket.on('some-socket-message', socket => {
// Whatever you want to do
});
app.get('/some-endpoint', (req, res) => {
// whatever you want to do
});
}
module.exports = {initialize}
And then add the following to your controller.js
const controller1 = require('path/to/controller1');
...
// At some point after socket and app have been defined
controller1.initalize(socket, app);
This will be the bases of separating your controller however you want, while still using the same socket connection and API port in all of your controllers. You can also refactor the initialize method into different methods, but that would be at your own discretion and how you want to name functions, etc. It also does not need to be called initalize, that was just my name of preference.
On my debian server, I installed node and then started node server on port 3000. The server is running, but it isn't visible from the browser
Now when I try to get it running via my domain or via my ip(for example xx.xxx.xx.xx:3000) or my domain (my-domain.com:3000) in both cases it doesn't work. I think I don't quite get the concept and I tried to search for a billion different things, but I can't find the solution to my problem. Could someone tell me, if I need to setup something else, too?
My server js code is
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);
server.listen(3000, () => {
console.log('listening on *:3000');
});
io.on('connection', function (socket) {
socket.on( 'new_message', function( data ) {
io.sockets.emit( 'new_message', {
message: data.message,
date: data.date,
msgcount: data.msgcount
});
});
});
Error i got
You need to listen for GET requests in order to respond to them.
Try adding something like:
app.get('/', function (req, res) {
res.send('GET request test.')
})
In your case make sure you add the route before passing the app to the http.createServer() method, or otherwise just use something like app.listen(3000).
More info in the docs: https://expressjs.com/en/guide/routing.html
why are you using express and http both packages.
you can run server by either of them.
and then add a get route for it.
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {
// ...
});
io.on("connection", (socket) => {
// ...
});
httpServer.listen(3000);
I hope this will work!
I am wondering how can i make socket.io avail outside my app.js page. I have currently all my socket related code on the app.js page after
const express = require('express');
const app = express();
const socketio = require('socket.io
const expressServer = app.listen(9999);
const io = socketio(expressServer);
where i can use the io.xxx but what i rather would do is to initialize the socket.io and then put all related code into a separate file where i can then expose functions to call emits etc.
You can put the socket.io code in it's own module and use exports to initialize and share the instance.
sio.js
const socketio = require('socket.io');
let io;
module.exports = {
init: function(server) {
if (io) {
throw new Error("socket.io already initialized");
}
// initalize socket.io to this server
io = socketio(server);
// put other socket.io initialization code here
return io;
}
get: function() {
if (!io) {
throw new Error("socket.io has not yet been initialized");
}
return io;
}
}
app.js
const express = require('express');
const app = express();
const expressServer = app.listen(9999);
const io = require('sio').init(expressServer);
some other module file that wants access to socket.io instance
const io = require('sio').get();
This allows one socket.io instance bound to one server per process (because the io instance is stored in module data). It could be extended to support multiple instances for multiple servers, but you'd then have to say which server you wanted the instance for when requesting the instance.
Note also that the .init() method must be called before the .get() can be called so the sio module should be loaded and call .init() on it early in the app module's setup before it loads other things that themselves might want to load sio.
I am on the process of building a chat application with nodejs, reactjs mongo and socket.io.My chat app consists of both one to one and group chats.I have built a schema for group chat and i am inserting group names along with its members and their chats in the table.Since im a beginner towards socket.io, I dont know where to put the socket logic that needs to be fired after the db post operation.Can some one suggest any examples for me?
Update your code accordingly:
=> server.js file
// Declare socket.io
const io = require('socket.io')(server);
// Add middleware to set socket.io in
app.use((req, res, next)=>{ res.locals['socketio'] = io; next(); });
=> In your controller file
// Get the value of socket.io
module.exports = your_function_name = (req, res) => {
const io = res.locals['socketio']
// Use io when you need.
});
Hope this solves your query.
You can separate you socket related code by following way :
==>app.js
var express = require('express');
var socket = require('./socketServer');
var app = express();
var server = app.listen((config.node_port || 3000), function () {
console.log('Listening on port ' + (config.node_port || 3000) + '...');
});
socket.socketStartUp(server);
module.exports = app;
==>socketServer.js
var io = require('socket.io')();
var socketFunction = {}
socketFunction.socketStartUp = function (server) {
io.attach(server);
io.on('connection', function (socket) {
console.log("New user is connected with socket:", socket.id);
})
}
module.exports = socketFunction;
You can also check node API startup code with socket functionality in below link:
Node API Start up
Hope this answer is helpful to you