创建一个独立的 Java websocket 客户端端点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21838940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:00:18  来源:igfitidea点击:

Create a standalone Java websocket client endpoint?

javawebsocketclient

提问by Tyler Durden

I want to create a websocket endpoint clientin Java (as pure as possible, no frameworks), but virtually all the examples I have found have only server endpoints in Java, whereas the client is in Javascript. Can anyone point me to a good client example, or provide one?

我想用 Java创建一个 websocket 端点客户端(尽可能纯,没有框架),但几乎我发现的所有示例都只有 Java 中的服务器端点,而客户端是 Javascript。谁能给我指出一个好的客户例子,或者提供一个?

采纳答案by lorinpa

Not sure if this fits your criteria, but Jetty has a pretty clean client example here:

不确定这是否符合您的标准,但 Jetty 在这里有一个非常干净的客户端示例:

http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html

http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html

Hope that helps :)

希望有帮助:)

回答by Leo

@ClientEndpointannottation is part of the spec, so I'd suggest to use that, here is a good tutorial , see step 4 and 6 .

@ClientEndpoint注释是规范的一部分,所以我建议使用它,这是一个很好的教程,请参阅步骤 4 和 6。

Step 6 from Openshift tutorial

Openshift 教程中的第 6 步

 @ClientEndpoint
public class WordgameClientEndpoint {

private static CountDownLatch latch;

private Logger logger = Logger.getLogger(this.getClass().getName());

@OnOpen
public void onOpen(Session session) {
    // same as above
}

@OnMessage
public String onMessage(String message, Session session) {
    // same as above
}

@OnClose
public void onClose(Session session, CloseReason closeReason) {
    logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
    latch.countDown();
}

public static void main(String[] args) {
    latch = new CountDownLatch(1);

    ClientManager client = ClientManager.createClient();
    try {
        client.connectToServer(WordgameClientEndpoint.class, new URI("ws://localhost:8025/websockets/game"));
        latch.await();

    } catch (DeploymentException | URISyntaxException | InterruptedException e) {
        throw new RuntimeException(e);
    }
}

}

}

in this example they are using tyrus, which is the reference implementation for websockets in java, so I think that meets your requirement of a well backed websocket implementation.

在这个例子中,他们使用tyrus,它是 java 中 websockets 的参考实现,所以我认为这满足了你对一个有良好支持的 websocket 实现的要求。