mrniko / netty-socketio

Socket.IO server implemented on Java. Realtime java framework
Apache License 2.0
6.82k stars 1.65k forks source link

Connecting React Client to Net SocketIO Backend results in 404 error #973

Open myselfuser1 opened 7 months ago

myselfuser1 commented 7 months ago

I am trying to connect my Next.js frontend to Spring boot backend in which I am using netty socketio server

I get 404 error in browser console

Screenshot 2024-04-10 at 8 06 55 AM

This is my backend code

@Configuration
public class SocketIOConfig {

    @Bean
    public SocketIOServer socketIOServer() {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        // config.setHostname(host);
        // config.setPort(8081);
        return new SocketIOServer(config);
    }
}

I also added cors in my main application class

@Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<>();
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        source.registerCorsConfiguration("/**", config);
        registrationBean.setFilter(new CorsFilter(source));
        registrationBean.setOrder(0);
        return registrationBean;
    }
@Component
public class SocketIOServerRunner implements CommandLineRunner {

    private final SocketIOEvents socketIOEvents;

    @Autowired
    public SocketIOServerRunner(SocketIOEvents socketIOEvents) {
        this.socketIOEvents = socketIOEvents;
    }

    @Override
    public void run(String... args) {
        socketIOEvents.init();
    }
}
@Component
public class SocketIOEvents {
    private final SocketIOServer server;

    @Autowired
    public SocketIOEvents(SocketIOServer server) {
        this.server = server;
    }

    public void init() {
        server.addConnectListener(client -> {
            System.out.println("Client connected: " + client.getSessionId());
            server.getBroadcastOperations().sendEvent("messageFromServer", "Client connected: " + client.getSessionId());
        });

        server.addDisconnectListener(client -> {
            System.out.println("Client disconnected: " + client.getSessionId());
        });

        server.addEventListener("messageFromClient", String.class, (client, data, ackSender) -> {
            System.out.println("Received message: " + data);
            server.getBroadcastOperations().sendEvent("messageFromServer", data);
        });
    }
}

This is my frontend NextJs code

"use client";

import { useEffect, useState } from "react";
import { io } from "socket.io-client";

export default function Home() {
  const [input, setInput] = useState("");
  const [messages, setMessage] = useState<string[]>([]);

  const socket = io("http://localhost:8080");

  useEffect(() => {
    socket.on("connect", () => {
      console.log(socket.id);
    });

    socket.on("messageFromServer", (data) => {
      console.log(data);
      setMessage((oldArray) => [...oldArray, data.data]);
    });

    socket.io.on("reconnect", (data) => {
      console.log("reconnect event");
      console.log(data);
    });
  }, []);

  const onChangeHandler = (event: any) => {
    setInput(event.target.value);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      <input type="text" onChange={onChangeHandler} value={input} />
      <button
        onClick={() => {
          console.log("[here](https://github.com/BraveEvidence/DemoNeetyV2)");
          socket.emit("messageFromClient", { data: input });
        }}>
        Submit
      </button>
      {messages.map((item, index) => {
        return <h5 key={`${index}`}>{item}</h5>;
      })}
    </div>
  );
}

Complete source code here

Encountering a 404 error in the browser console when trying to connect your Next.js frontend to your Spring Boot backend using Netty Socket.IO server

shutuper commented 6 months ago

Your filter is applied only for Spring web server, but netty-socket.io starts separate netty server and uses another port which you can specify in com.corundumstudio.socketio.Configuration, it also contains getter/setter methods for allowed origin and headers

myselfuser1 commented 6 months ago

@shutuper Thanks for the reply. I updated the code to

@Configuration
public class SocketIOConfig {

    @Bean
    public SocketIOServer socketIOServer() {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setPort(8081);
        config.setOrigin("*"); // Allow requests from all origins
        return new SocketIOServer(config);
    }
}

But still i get cors issue, I am accessing http://localhost:8081 from frontend side