简体   繁体   中英

Cannot connect to java websocket server

I am trying to create a simple websocket java chat. But I am having an incredible struggle trying to figure out what is the problem here and why I receive " Firefox can't establish a connection to the server at ws://localhost:8080/ivan-stanev-client/chat/a ". I have a simple web socket java server:

@ServerEndpoint(value = "/chat/{username}", decoders = MessageDecoder.class, encoders = MessageEncoder.class)
public class ChatEndpoint {
    private Session session;
    private static final Set<ChatEndpoint> chatEndpoints = new CopyOnWriteArraySet<>();
    private static HashMap<String, String> users = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) throws IOException, EncodeException {

        this.session = session;
        chatEndpoints.add(this);
        users.put(session.getId(), username);

        Message message = new Message();
        message.setFrom(username);
        message.setContent("Connected!");
        broadcast(message);
    }
...

And this is the part that creates the error in the javascript(no idea why I cannot establish a connection, I searched everywhere):

    ws = new WebSocket("ws://" + document.location.host + "/ivan-stanev-client/chat/" + username);

PS I am following this tutorial: https://github.com/eugenp/tutorials/tree/c83c449fa5a7ac2462fabf0ed26969f1b037aa12/java-websocket

What was the issue? Tomcat uses ServletContainerInitializer to find any classes annotated with ServerEndpoint in an application. Spring Boot, on the other hand, doesn't support ServletContainerInitializer when you're using any embedded web container.

Therefore, we need to export our ServerEndpoint by creating a bean of ServerEndpointExporter. WebSocketConfig class had to be created in the application.

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

Also I was missing a @Component annotation on the WebSocket Server.

-- Credits http://thegeekyasian.com/websocket-in-spring-boot/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM