Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get socket.io working with ES6 import modules?

I refactored a simple example of socket.io from CommonJS require syntax to ES6 import syntax but when I start the server and go to the website, although it shows the HTML text ("test from server.js"), it doesn’t inform the server that it is connected.

Yet there are no errors in the console at all, it just acts as if socket.io is not loading at all.

In my package.json file, I have the following entry in order that ES6 modules work in Node:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"type": "module",

Why is socket.io not working?

server.js

import path from 'path';
import http from 'http';
import express from 'express';
import { Server as socketIO } from 'socket.io';

const app = express();
const PORT = 5011;
const __dirname = path.resolve(path.dirname(''));
const server = http.Server(app);
const io = new socketIO(server);

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

io.on('connection', (socket) => {
    console.log('user connected');
    socket.emit('greeting-from-server', {
        greeting: 'you loaded the page'
    });
})

app.listen(PORT, () => {
    console.log(`listening on port http://localhost:${PORT}`);
});

/public/index.html

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Socket.IO</title>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const socket = io('http://localhost:5011');
        socket.on('greeting-from-server', (data) => {
            console.log(data);
            socket.emit('greeting-from-client', {
                greeting: 'Hello Server'
            });
        });
    </script>
</head>

<body>
    test from server.js
</body>

</html>

>Solution :

import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {
  // ...
});

io.on("connection", (socket) => {
  // ...
});enter code here

httpServer.listen(3000);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading