Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
myselfuser1 opened this issue Apr 10, 2024 · 2 comments
Open

Comments

@myselfuser1
Copy link

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
Copy link
Contributor

shutuper commented Apr 27, 2024

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
Copy link
Author

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants