我目前正在使用 Glassfish 4 和“板载”实现测试 Websockets,但无法发送或接收任何消息,尽管遵循Java EE 7 教程 - 发送和接收消息或如何使用 JSR 356 API 构建 Java WebSocket 应用程序等教程。我想实现一个简单的客户端服务器通信,所以我只有一个
服务器:
@ServerEndpoint("/echotest")
public class Server {
private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);
@OnOpen
public void onOpen(Session session) {
LOGGER.info("OnOpen invoked by Session '{}'.", session.getId());
try {
session.getBasicRemote().sendText("Hello Client!");
} catch (IOException ex) {
LOGGER.error("Message delivery failed.", ex);
}
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
LOGGER.info("OnClose invoked by Session '{}'; Reason: {}.", session.getId(), closeReason.getReasonPhrase());
}
@OnMessage
public void onMessage(Session session, String msg) {
LOGGER.info("OnMessage invoked by Session '{}'; Message: {}.", session.getId(), msg);
}
}
和一个客户:
@ClientEndpoint
public class Client {
private static CountDownLatch latch;
private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
@OnOpen
public void onOpen(Session session) {
LOGGER.info("OnOpen invoked by Session '{}'.", session.getId());
try {
session.getBasicRemote().sendText("Hello Server!");
} catch (IOException ex) {
LOGGER.error("Message delivery failed.", ex);
}
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
LOGGER.info("OnClose invoked by Session '{}'; Reason: {}.", session.getId(), closeReason.getReasonPhrase());
}
@OnMessage
public void onMessage(Session session, String msg) {
LOGGER.info("OnMessage invoked by Session '{}'; Message: {}.", session.getId(), msg);
}
public static void main(String[] args) {
latch = new CountDownLatch(1);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
try {
container.connectToServer(Client.class, new URI("ws://localhost:8080/Tstr/echotest"));
latch.await();
} catch (DeploymentException | URISyntaxException | InterruptedException | IOException e) {
LOGGER.error("Connection error occured!", e);
}
}
}
Websocket 可用,我可以连接到服务器(更改 URI 会导致 404 握手错误),但不会调用任何(服务器端)方法,我得到的唯一日志消息是:
INFO: OnOpen invoked by Session 'acc92925-6682-4414-9e78-cf60a624b014'.
在客户端。我希望服务器至少记录 onOpen 调用。使用带有 Netbeans 8 的(未改动的)Glassfish 4 进行此测试。
有什么建议为什么没有交换消息?