0

guys, I am new with websockets. I try recreate the common live chat example with NodeJs socket server and React StompJs client. On server-side I have receive the client connection. When refresh the client page server note disconnect and after that connects the client again. The problem is with my react client. It doesn't notes the connection with the server. It never gets in the "onConnect" property. Do you have any idea what's wrong here? Thanks :)

Here is my server code:

const WebSocket = require("ws");
const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("WebSocket server is running");
});

const wss = new WebSocket.Server({ server });

wss.on("connection", (ws, req) => {
  ws.send("test -> ");
  console.log("Client connected");

  ws.on("message", (message) => {
    console.log("Received message:", message);
    ws.send(message);
  });

  ws.on("close", () => {
    console.log("Client disconnected");
  });
});

const port = 8080;
server.listen(port, () => {
  console.log(`WebSocket server is listening on port ${port}`);
});

Here is my React Client:

import React, { useEffect, useState } from "react";
import { Client } from "@stomp/stompjs";

function App() {
  const [stompClient, setStompClient] = useState(null);
  const [isConnected, setIsConnected] = useState(false);
  const [message, setMessage] = useState("");
  const [receivedMessages, setReceivedMessages] = useState([]);


  useEffect(() => {
    const client = new Client({
      brokerURL: "ws://localhost:8080",
      onConnect: () => {
          console.log("connected to webscoket server");
          setIsConnected(true);
          setStompClient(client);
        },
      reconnectDelay: 5000,
      debug: (str) => console.log(str),
    });
    
    client.onStompError = (frame) => {
      console.error("STOMP error:", frame.headers.message);
    };

    client.activate();
    
    return () => {
      if (stompClient) {
        stompClient.deactivate();
      }
    };
  }, [stompClient]);

  const handleSendMessage = () => {
    if (stompClient && stompClient.connected && message.trim() !== "") {
      stompClient.publish({ destination: "/app/sendMessage", body: message });
      setMessage("");
    }
  };

  useEffect(() => {
    if (stompClient && isConnected) {
      console.log("subscribe");
      const subscription = stompClient.subscribe(
        "/topic/messages",
        (message) => {
          const receivedMessage = JSON.parse(message.body);
          setReceivedMessages((prevMessages) => [
            ...prevMessages,
            receivedMessage,
          ]);
        }
      );

      return () => {
        subscription.unsubscribe();
      };
    }
  }, [stompClient, isConnected]);

Here is what I have in the client console: Opening Web Socket... Web Socket Opened...

CONNECT accept-version:1.2,1.1,1.0 heart-beat:10000,10000

Received data <<< test -> CONNECT heart-beat:10000,10000 accept-version:1.2,1.1,1.0 content-length:0

0 Answers0