can i connect client server(localhost:8082) and websocket(localhost:8080)?

990 Views Asked by At

My problem is I need to connect different port or server! websocket server(localhost:8080) client server(localhost:random) (failed: Error during WebSocket handshake: Unexpected response code: 403) why?? I'm tired...

I already tried same port and I can success! I can connect client(localhost:8080) and websocekt(localhost:8080).

I want to use websocket using (server side: java sts, tomcat 8.0).

questions 1. websocket can connect only same server and port???!!!!(no! please!) 2. If I can... what's the problem :(? Do u have any example?

2

There are 2 best solutions below

0
On BEST ANSWER
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler(), "/myHandler").setAllowedOrigins("*");
    }
    @Bean
    public WebSocketHandler myHandler() {
        return new MyHandler();
    }
}
6
On

Sounds like this is related to CORS https://en.wikipedia.org/wiki/Cross-origin_resource_sharing. I assume you are using spring websocket as you didn't mention.

You will need to disable same origin policy in your websocket config class as below example,

@Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {

@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {

}

@Override
protected boolean sameOriginDisabled() {
    //disable CSRF for websockets 
    return true;
}