简体   繁体   中英

Is there a minimalist WebSocket client library for java?

The title says it all.

I'm trying to make a video game that connects to a server hosted on heroku for file verification.

Since heroku doesn't support vinella sockets I have to use websockets. I can make a websocket server just fine with Ruby or with some big java framework but I can't find a lightweight solution for making a client socket with java.

Thanks in advance!

JSR 356 (Java API for WebSocket) , part of Java EE 7 defines client API. There are multiple implementations: Tyrus (glassfish/WLS), Tomcat, ...; basically every container do provide the implementation or this api, even if not implementing other Java EE 7 specifications.

Simple example:

        final WebSocketContainer client = ContainerProvider.getWebSocketContainer();
        final Session session = client.connectToServer(new Endpoint() {
            @Override
            public void onOpen(Session session, EndpointConfig EndpointConfig) {

                try {
                    session.addMessageHandler(new MessageHandler.Whole<String>() {
                        @Override
                        public void onMessage(String message) {
                            System.out.println("### Received: " + message);
                        }
                    });

                    session.getBasicRemote().sendText("Do or do not, there is no try.");
                } catch (IOException e) {
                    // do nothing
                }
            }

            @Override
            public void onClose(Session session, CloseReason closeReason) {
                System.out.println("### Client session closed: " + closeReason);
            }
        }, ClientEndpointConfig.Builder.create().build(), URI.create("ws://echo.websocket.org"));

You can check Client Endpoint chapter in Tyrus user guide for more details.

Jetty has WebSocket Client API

Jetty WebSocket Client API

Just for completeness in future search hits, JavaSE 11 now has WebSocket support as well, in the java.net.http package .

Although I confess I'm finding only basic documentation and simplistic examples so far. Which leaves a bit to be desired in implementing a complete, robust solution. Among other things, a decent understanding of Java Concurrency seems to be required.

There's a little bit here: Require assistance with simple pure Java 11 WebSocket client example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM