Tips for setting up a socketIO server alongside a main server in Node.js

At the moment, our main server is being hosted on localhost:3000. In order to run our socket.io function, we must also run it on the same server. However, we currently need to run it separately using npm start. Is there a method for running them simultaneously or on the same server without causing crashing issues?

Answer №1

Using socket.io in a separate process is not possible, as the operating system only allows one process to have a listening server on a specific port. If you want to run socket.io alongside another web server, you can do so by using a proxy like nginx to direct traffic to different servers on different ports.

If you are considering starting "npm start separately," there may be a better way to solve your underlying issue without needing to split the servers into separate processes. It's important to understand the actual problem at hand rather than focusing on a specific solution that may not be the most effective approach.

By properly defining the problem, we can explore alternative solutions such as delaying the start of the socket.io server or configuring the servers to meet certain requirements before allowing connections. This way, we can address the real issue at hand rather than getting caught up in potential XY problems.

Answer №2

This is a straightforward example of SocketIo Server Code. Remember, this is the server-side code and not for the client.
Make sure to install SocketIO via npm.

const express = require('express');
const http = require('http');
const SocketIo = require('socket.io');

const app = express();

app.set('view engine', 'pug');
app.set('views', __dirname + '\\views');
app.use('/public', express.static(__dirname + '/public'));

app.get('/', (req, res) => res.render('home'));

const handleListen = () => console.log('Listening on http://localhost:3000');

const httpServer = http.createServer(app);
const wsServer = SocketIo(httpServer);

wsServer.on('connection', (socket) => {
  console.log('someone joined!')
  socket.on('join_room', (roomName) => {
    socket.join(roomName);
    socket.to(roomName).emit('welcome');
  });
});

httpServer.listen(3000, handleListen);

For further information, please refer to the official documentation. https://socket.io/get-started/chat

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

missing method in HTML/JavaScript

Just experimenting with functions and time... The outcome is showing as undefined on the live server. However, if I execute the JavaScript code separately, the correct greetings display. Why is this happening? Is there a solution to rectify it? const tod ...

Tips for converting API data to DTO (Data Transfer Object) using TypeScript

Here is an array of vehicles with their details. export const fetchDataFromApi = () => { return [ { vehicleId: 1, vehicleType: 'car', seats: 4, wheelType: 'summer', updatedAt: new Date().toISOString }, { vehicleId: 2, vehic ...

Which element is undefined in this scenario - the Event Object or the inputs?

While working on OTP verification in Reactjs, I encountered an error message when running my code: Error: Cannot read properties of undefined (reading 'value') import { useState, useEffect, useRef } from 'react' import '../src/ ...

Angular array: showcasing both keys and values in an efficient manner

Within my Angular code, I have created an array structured like this: $scope.test = [ {'item1' : 'answer1' }, {'item2' : 'answer2' }, {'item3' : 'answer3' } ]; This array contains various ...

Gravity Forms Dropdown Selections Aren't Visible

I recently made a modification to the footer.php file by adding the following code: <div class="footer-email-form-container"> <?php echo do_shortcode( '[gravityform id="26" title="true" description="false"]' ); ?></div> Howeve ...

Enhancing unique designs

After searching for a background pattern, I stumbled upon this unique design. Currently, I have it as the backdrop for my website. The issue arises from the fact that this pattern doesn't seamlessly repeat. When I set it as the body background usin ...

What could be causing the errors in my subscription function?

Working on an e-commerce website, I encountered errors in the "cartservice" specifically in the "checkoutFromCart()" function. The console displayed the following error: src/app/services/cart.service.ts:218:81 218 this.http.post(${this.serverUrl}ord ...

Passing a textbox's value through an AJAX call from a ServerSide datatable in MVC5

I am encountering an issue with my server-side data-table. After making an ajax call, the value from the text box is not being sent - instead, it is sending an empty value. However, everything works fine when I pass static data. Here is the code that wo ...

Searching with nested strings for keys in JavaScript using JSON structures

Given a json object in JavaScript like so: var data = { blog : { title: "my blog", logo: "blah.jpg", }, posts : [ { title: "test post", content: "<p>testing posts</p><br><p&g ...

What is the best method for validating multiple fields in a form with Javascript?

I am currently working on validating multiple fields within a form. Although I lack experience in JavaScript, I have managed to piece together a code that is functional for the most part. If all fields are left blank, error messages prompt correctly. Howe ...

Is there a way to show output on render rather than using console.log in node.js?

I have successfully sorted the objects as shown in the link below. My next challenge is to integrate the sorted object into my render function rather than just using console.log(). I'm uncertain if converting it back into an object is the right appro ...

Why does Axios keep timing out despite successful testing in Postman?

Trying to set up a single request for my app using axios with express/node js. Here is the code snippet that was generated through the Postman app. I have attempted different variations by creating my own form, but I always end up with the same result. co ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Locating terms within two attributes of a MongoDB record

Searching for a word from two properties, 'firstname' and 'lastname', in a document has been challenging. The current code is not providing the expected response when searching through multiple properties. As a beginner in mongo db, I w ...

Is there a way to conditionally redirect to a specific page using NextAuth?

My website has 2 points of user login: one is through my app and the other is via a link on a third-party site. If a user comes from the third-party site, they should be redirected back to it. The only method I can come up with to distinguish if a user is ...

Choose all the HTML content that falls within two specific tags

Similar Question: jquery - How to select all content between two tags Let's say there is a sample HTML code as follows: <div> <span> <a>Link</a> </span> <p id="start">Foo</p> <!-- lots of random HTML ...

What is the best way to include the parameter set in the interceptor when making a post request?

-> Initially, I attempt to handle this scenario in the axios request interceptor; if the parameter is uber, then utilize a token. If the parameter is not uber, then do not use a token. -> Afterward, how can I specify uber as a parameter in the custo ...

Responsive Tabs with Material-UI

Can MUI's Tabs be made responsive? This is what I currently have: https://i.stack.imgur.com/KF8eO.png And this is what I aim to accomplish: https://i.stack.imgur.com/b3QLc.png ...

How can I use jQuery to identify the numerical range within class/td/div elements and modify their CSS styles?

1# I need assistance in changing the CSS properties of a TD, Class, and div using a selector that specifies a specific number range. Specifically, I am looking to modify the css of torrent results with a seed count between 250-25000. Any torrents with a se ...

An error occurs when attempting to upload an image in cropper js due to a violation of the Content Security Policy directive: "img-src * data:"

I'm currently using cropperjs to crop an image upon uploading click here to see the button Once the image is selected for upload, I encounter this problem The data in blob storage remains intact, but there seems to be an issue after the image is upl ...