Payara Javax websocket 连接失败,没有消息

时间:2021-03-09 13:49:47

标签: java websocket payara-micro

我正在尝试在正在运行的 REST 应用程序上创建一个 websocket 服务器,但它没有像我预期的那样工作(它根本不起作用)......我是 Java/Javax 的新手,我不知道我做错了什么。我不负责 REST API 的创建,但我知道它运行良好。它由 Payara Micro 5.2020.2 和 openjdk 11.0.11 提供支持,并使用 Gradle 构建。

我在 domain.xml 文件中启用了 websockets 支持:

<domain>
  <!-- resources, servers, etc. -->
    <configs>
      <config name="server-config">
        <!-- some services -->
        <network-config>
          <protocols>
            <protocol>
              <http default-virtual-server="server" xpowered-by="false" max-connections="250"  comet-support-enabled="true" websockets-support-enabled="true"/>
            </protocol>
          </protocols>
          <!-- network-listeners, transports, etc. -->
        </config>
    </configs>
</domain>

我创建了一个简单的端点类来通过 websocket 进行通信:

package my.app.websockets;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import javax.enterprise.context.ApplicationScoped;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.*;

@ApplicationScoped
@ServerEndpoint(value = "/ws")
public class FooEndpoint extends Endpoint {
    private static final Logger LOGGER = LoggerFactory.getLogger(FooEndpoint.class);
    private static final Collection<Session> sessions = Collections.synchronizedCollection(new ArrayList<>());

    @Override
    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        LOGGER.info("Connected");
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        LOGGER.info("Message");
    }

    @Override
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        LOGGER.info("Disconnected");
    }

    @Override
    @OnError
    public void onError(Session session, Throwable throwable) {
        LOGGER.error("Error", throwable);
    }
}

REST API est 在 http://localhost:8081/my-app 上提供服务,所以我猜 websocket 使用相同的主机名和端口,但是当我尝试创建 web socket客户端时,连接失败。

const ws1 = new WebSocket("ws://localhost:8081/my-app/ws");
// WebSocket connection to 'ws://localhost:8081/my-app/ws' failed: 

const ws2 = new WebSocket("ws://localhost:8081/ws");
// WebSocket connection to 'ws://localhost:8081/ws' failed: 

我不知道是由于错误的 URL 还是错误的配置。你能帮我吗?

0 个答案:

没有答案
相关问题