0

So I am trying to build a dynamic dashboard application ,so I use socket io 4.8.1 , and In frontend as well I installed the same version , now I used polling socket io it actually worked with polling method but when I try websocket transport it's not working , i get this error message as

Error as Error connecting to socket TransportError: websocket error at WS.onError (transport.js:39:33) at ws.onerror [as __zone_symbol__ON_PROPERTYerror] (websocket.js:44:33) at WebSocket.wrapFn (zone.js:778:39) at _ZoneDelegate.invokeTask (zone.js:402:33) at core.mjs:6717:49 at AsyncStackTaggingZoneSpec.onInvokeTask (core.mjs:6717:30) at _ZoneDelegate.invokeTask (zone.js:401:38) at Object.onInvokeTask (core.mjs:7037:25) at _ZoneDelegate.invokeTask (zone.js:401:38) at ZoneImpl.runTask (zone.js:159:47)

My angular code :

connectSocket() {
  this.socket = io("http://localhost:3000", {
    transports: ["websocket"], // forcing WebSocket
  });

  this.socket.on("connect", () => {
    console.log("✅ Connected to socket");
  });

  this.socket.on("connect_error", (error) => {
    console.log("❌ Error connecting to socket", error);
  });

  this.socket.on("connect_timeout", (error) => {
    console.log("⏱️ Timeout connecting to socket", error);
  });

  this.socket.on("reconnect_error", (error) => {
    console.log("♻️ Error reconnecting to socket", error);
  });

  this.socket.on("reconnect_failed", (error) => {
    console.log("🚫 Failed to reconnect to socket", error);
  });
}

I saw only connecting to Socket bit not connected log

My backend

Socket file

const { Server } = require("socket.io");

async function setUpSocket(server) {
  const io = new Server(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"],
    },
  });

  console.log("⚡ Socket.IO server initialized (socket-handler.js)");

  io.on("connection", (socket) => {
    console.log("✅ Socket connected:", socket.id);

    socket.on("disconnect", () => {
      console.log("🔌 Socket disconnected:", socket.id);
    });

    socket.on("dashboard-socket", (dbID) => {
      if (!dbID) return;

      if (socket.dbID) {
        socket.leave(socket.dbID);
        console.log(`🚪 Socket ${socket.id} left room: ${socket.dbID}`);
      }

      socket.join(dbID);
      socket.dbID = dbID;
      console.log(`🏠 Socket ${socket.id} joined room: ${dbID}`);
    });

    socket.on("error", (err) => {
      console.error("⚠️ Unhandled socket error:", err);
    });
  });

  global.io = io;
}

module.exports = setUpSocket;

Main app.js nodejs file :

const express = require("express");
const http = require("http");
const path = require("path");
const bodyParser = require("body-parser");
const cors = require("cors");
const { configDotenv } = require("dotenv");
const setUpSocket = require("./sockets/socket-handler.js");

const app = express();
const server = http.createServer(app);

global.appRoot = path.resolve(__dirname);
configDotenv();

// Static files and view engine
app.use("/public", express.static(path.join(__dirname, "public")));
app.set("view engine", "hbs");
app.set("views", path.join(__dirname, "views"));

// CORS setup
app.use(cors({ origin: "*", methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"] }));

// Body parser
app.use(bodyParser.json({ limit: "100mb" }));
app.use(bodyParser.urlencoded({ limit: "100mb", extended: true, parameterLimit: 50000 }));

// Initialize Socket.IO
setUpSocket(server);

// Start server
server.listen(3000, () => {
  console.log("✅ Server started on port 3000");
});

1 Answer 1

0

Check WebSocket URL in the Client

The issue might be related to using the wrong URL for the WebSocket connection. If you're using http://localhost:3000 for Socket.IO connection, it will work with polling transport, but for WebSocket, you need to use a URL starting with ws:// (for HTTP) or wss:// (for HTTPS).

Solution:

Update your Angular code to force WebSocket transport as follows:

this.socket = io("ws://localhost:3000", {
  transports: ["websocket"], // Force WebSocket transport
});

If your server is using HTTPS, change the URL to wss:// like this:

this.socket = io("wss://localhost:3000", {
  transports: ["websocket"], // Force WebSocket transport
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.