1

I created a Spring WebSocket server.
I want to real-time connection with Unity webgl.

It works well when I connect with postman.

It works well on Unity Game Scene.

 async void Start()
 {
     Debug.Log("Starting WebSocket connection...");

     clientId = System.Guid.NewGuid().ToString();
     ws = new WebSocket("wss://unbiased-evenly-worm.ngrok-free.app/game");

     ws.OnOpen += () =>
     {
         Debug.Log("WebSocket connected!");
     };

     ws.OnMessage += (byte[] msg) =>
     {
         string message = Encoding.UTF8.GetString(msg);
         Debug.Log("Message received: " + message);
         OnMessageReceived(message);
     };

     ws.OnError += (string errMsg) =>
     {
         Debug.LogError("WebSocket error: " + errMsg);
     };

     ws.OnClose += (WebSocketCloseCode code) =>
     {
         Debug.LogWarning("WebSocket closed with code: " + code.ToString());
     };

     Debug.Log("Attempting to connect WebSocket...");
     try
     {
         await ws.Connect();
         Debug.Log("WebSocket connection successful.");
     }
     catch (System.Exception ex)
     {
         Debug.LogError("WebSocket connection failed: " + ex.Message);
     }

     targetPosition = transform.position;

     Cursor.lockState = CursorLockMode.Locked;
     Cursor.visible = false;
 }

I think it's not working in the browser, it's like a cors error

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    private final JWTUtil jwtUtil;

    public SecurityConfig(JWTUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return web -> web.ignoring()
                .requestMatchers("/error", "/favicon.ico");
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .formLogin(formLogin -> formLogin.disable())
                .httpBasic(httpBasic -> httpBasic.disable())
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/login", "/", "/join", "/verify-id", "/register", "/check-email", "/verify-email", "/verify-test", "/oauth/google", "/oauth/kakao", "/oauth","/profile/**","/refresh", "/reset-password","/reset-password-auth","/game/**","upload","/image","/game").permitAll()
                        .anyRequest().authenticated()
                )
                .addFilterBefore(new JWTFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class)
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                );
        return http.build();
    }
}

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new GameWebSocketHandler(), "/game")
                .setAllowedOrigins("*"); 
    }
}

Is there anything wrong with the spring or Unity code?

enter image description here

Changing the server address to ws://localhost:8080/game works well on the web(server is running on my local)

Can connection from postman to "wss://unbiased-evenly-worm.ngrok-free.app/game"

It is currently deployed using ngrock

1 Answer 1

0

This may be an SSL certificate issue. What certificate does your WebSocket server use? If it's just a self-signed certificate Unity will refuse to connect.

Have you tried to connect to the server via the browser console by directly typing javascript? In most cases it's the browser's security that will refuse the connection since self-signed certificates are considered unsafe.

Another important question is what WebSocket class are you actually using in Unity? It has to be a Unity specific implementation that actually wraps the native javascript WebSocket. You can not use any implementation that is based on .NET sockets as you can not make socket connections in a WebGL build.

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.