我目前正在使用Glassfish 4和#34; on"来测试Websockets。实施但不能发送或接收任何消息,尽管遵循The Java EE 7 Tutorial - Sending and Receiving Messages或How to build Java WebSocket Applications Using the JSR 356 API等教程。我想实现一个简单的客户端服务器通信,所以我只有一个
服务器:
@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 invokation。使用(未触动的)Glassfish 4和Netbeans 8进行此测试。
为什么没有交换消息的任何建议?
答案 0 :(得分:0)
你的代码对我有用,但我不得不用这个java.util.logging.Logger
替换Logger(slf4j?)