Well, it appears that I am having trouble establishing a connection between the users in this chatting application

I'm encountering a problem with establishing a connection between two users. I have already installed express and socket.io, but for some reason, the message is not getting through to the receiver's end. The code seems to be running fine as I can open the website without any issues. However, when I try to send a message from one page, it doesn't show up at the recipient's end.

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/chat', (req, res) => {
  res.sendFile(__dirname + '/chat.html');
});

io.on('connection', (socket) => {
  console.log('User Online');
  
  socket.on('codeboard-message', (msg) => {
    console.log('message: ' + msg);
    socket.broadcast.emit('message-from-others', msg);
  });
  
});

var server_port = process.env.YOUR_PORT || process.env.PORT || 3000;
http.listen(server_port, () => {
  console.log('listening on *:' + server_port);
});
<html>

    <head>
        <title> Chat </title>
        
        <style>
        
            * {
                font-family: sans-serif;
                margin: 0;
                padding: 0;
            }
        
            .header-area {
                height: 6%;
                background: rgb(0 127 255);
                box-shadow: 0 0.25rem 0.25rem rgba(0, 0, 0, 0.2), 0 0 1rem rgba(0, 0, 0, 0.2);
                color: white;
                padding: 4px;
            }
            
...

</html>

Answer №1

Check the Network tab in the inspector for an error 400 related to a request made to http://localhost:3000/socket.io/?EIO=3&transport=polling.

The error message displayed is

{"code":5,"message":"Unsupported protocol version"}
, indicating a compatibility issue between the client and server.

To resolve this, replace

var io = require('socket.io')(http);
with:

const io = require("socket.io")({
  allowEIO3: true // false by default
}).listen(http)

Make this change in your server file to ensure functionality!

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

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

Ways to solve the issue of the mobile dropdown menu in Bootstrap

Check Out the Expected Look Here (Image link) See How it Appears on Mobile Devices The dropdown menu causes an increase in the size of the navbar on the mobile version. Below is the code snippet: <div style=" background-image: url(https://i.imgu ...

Scrolling infinitely within the side menu using ion-infinite-scroll

I'm encountering an issue with using Ion-infinite-scroll within ion-side-menu, as the load more function is not being triggered. Is it permitted to utilize ion-infinite-scroll inside ion-side-menu? Although I have added the directive, the method "lo ...

Creating a mouse hover effect for irregular shapes on an image map

Is it possible to implement a mouse hover effect on irregular shapes within an image map? These irregular shapes are not basic polygons like rectangles, triangles, or circles, but rather complex designs such as lanterns or animals. Can this be achieved? ...

Utilize AngularJs and JavaScript to upload information to a JSON file

Exploring the realm of Angular JS, I am on a quest to create a CRUD form using AngularJs and Json with pure javascript without involving any other server side language. The script seems to be functioning well but is facing an obstacle when it comes to writ ...

The websocket connection established with apollo-server is somehow producing nonsensical output for the connection params

onConnect should receive the connectionParams supplied by the client and then validate that the token has not expired by checking the token property on the connectionParams object. On the client-side, I send these parameters in the following manner: const ...

What is the best way to implement a CSS rule that is influenced by the number of siblings present within an element?

Is there a way to style an element differently based on the number of subelements it contains? <div class="wrapper"> <div class="element" /> </div> or... <div class="wrapper"> <div class="element" /> <div class="el ...

Cross-origin resource sharing (CORS) allows for the secure transfer of data across different

Currently, I am faced with a challenge in making an XmlHTTPRequest POST request from a page loaded via HTTPS to a different domain using an HTTP URL. The HTTP server in question is local and does not support HTTPS due to being within a home setup (like a s ...

Clicking on a dynamically generated link will not result in the file being downloaded

I have a list of document names and IDs retrieved from a database, displayed in an unordered list like this: <ul id="list"> <li onmouseover="onHover(docNumber)"> <a herf="#" id="docNumber">DocName</a> </li> </ ...

A Guide on Integrating a Javascript Reference into HTML while Displaying a PHP Object

Our website relies heavily on PHP modules to generate objects that are essential for constructing our web pages. Some of the key modules we have include: Anchor (ahref) Button CheckBox ComboBox DateTime Email Label Note Password Phone RadioButton RichTe ...

Error in Chrome: Text container's height is not fully extended to 100%

I'm encountering an issue with achieving 100% height on a child container in Google Chrome, although it works perfectly fine on Firefox. Here is the URL: http://linco.com.py/beta/multiplaza/cartelera.php The styling for the main container is as fol ...

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...

Reorganize JSON data in JavaScript

I am in the process of creating a tree structure, and I want it to be organized in the order of name, desc, then children. However, the JSON data I have received is not in this order. Is there a way to rearrange it efficiently or perhaps optimize the code ...

I'm noticing that my style.css changes are only showing up after a hard refresh, but then they revert back to an older version when I refresh normally

Apologies for the lengthy title. Here's the issue: I have a WordPress website with a custom theme and its corresponding child theme. Previously, updating the style.css file of the child theme would show the changes immediately after a website refresh ...

Attempting to store form data in a database using PHP has proven to be unsuccessful in my efforts

I am facing an issue while trying to add HTML form data into the database using PHP. Unfortunately, I am unable to successfully insert the HTML form data into the database and I'm not sure what mistake I might be making in my code. Below is the code ...

Having trouble parsing JSON that is stored as a string in Java

I'm having trouble reading text in JSON format from a website. I keep getting the error: Java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray This is really frustrating for me. Can someone provide ...

Encountering a TypeError while attempting to construct and launch an IOS simulator through Cordova

Currently, I am in the process of developing an Ionic app that is designed for cross-platform functionality. Encountering an Error when attempting to build and run an IOS simulator using Cordova TypeError [ERR_INVALID_ARG_TYPE]: The "code" argum ...

What is the best way to group a Pie Chart by a string field in a .csv file using dc.js, d3.js, and crossfilter.js in a Node environment?

I've successfully set up several Dimensions and groups, but I'm encountering an issue with a Pie Chart that needs to be grouped based on domain names like bing.com. Each domain name is parsed consistently to xxxx.xxx format and the data is clean. ...

Managing jQuery Dependency in Node Package

I am facing an issue while trying to implement the 'jvectormap' package in Node, as it has a dependency on jQuery. My query is fairly straightforward. Whenever I attempt to import jVectorMap, I encounter the following error: Uncaught ReferenceE ...

A guide to consuming JSON String arrays in Spring Boot

I'm facing issues with properly reading an input JSON file in my webservice. I'm trying to convert some input parameters from a simple String to an array of Strings The structure of my input JSON is as follows: { "inputParams" : { "speckle ...