【问题标题】:Cannot connect to java websocket server无法连接到 java websocket 服务器
【发布时间】:2020-07-04 03:01:55
【问题描述】:

我正在尝试创建一个简单的 websocket java 聊天。但是我很难弄清楚这里的问题是什么以及为什么我收到“Firefox 无法在 ws://localhost:8080/ivan-stanev-client/chat 建立与服务器的连接/a”。 我有一个简单的 web socket java 服务器:

@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);
    }
...

这是在 javascript 中创建错误的部分(不知道为什么我无法建立连接,我到处搜索):

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

附:我正在关注本教程:https://github.com/eugenp/tutorials/tree/c83c449fa5a7ac2462fabf0ed26969f1b037aa12/java-websocket

【问题讨论】:

    标签: javascript java websocket chat


    【解决方案1】:

    出了什么问题? Tomcat 使用 ServletContainerInitializer 来查找应用程序中使用 ServerEndpoint 注释的任何类。另一方面,当您使用任何嵌入式 Web 容器时,Spring Boot 不支持 ServletContainerInitializer。

    因此,我们需要通过创建 ServerEndpointExporter 的 bean 来导出我们的 ServerEndpoint。 WebSocketConfig 类必须在应用程序中创建。

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

    我也错过了 WebSocket 服务器上的 @Component 注释。

    -- 致谢http://thegeekyasian.com/websocket-in-spring-boot/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 2018-07-05
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多