question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Human-readable method names for web socket API (Java)

See original GitHub issue

Describe the feature

What about renaming the method names handle() in the websocket handler endpoints CloseHandler, MessageHandkler, ConnectHandler, and so on?

The target is to make Java class-based implementations more readable instead of having multiple handle() methods on the same class.

Additional context

Current

  private static class FooWebsocket implements CloseHandler, MessageHandler, ConnectHandler, ErrorHandler, BinaryMessageHandler {

    @Override
    public void handle(WsSession session) throws Exception {}

    @Override
    public void handle(WsSession session, String msg) throws Exception {}

    @Override
    public void handle(WsSession session, int statusCode, String reason) throws Exception {}

    @Override
    public void handle(WsSession session, Byte[] msg, int offset, int length) throws Exception {}

    @Override
    public void handle(WsSession session, Throwable throwable) throws Exception {}
  }

Idea 1

  private static class FooWebsocket implements CloseHandler, MessageHandler, ConnectHandler, ErrorHandler, BinaryMessageHandler {

    @Override
    public void onConnect(WsSession session) throws Exception {}

    @Override
    public void onMessage(WsSession session, String msg) throws Exception {}

    @Override
    public void onClose(WsSession session, int statusCode, String reason) throws Exception {}

    @Override
    public void onBinaryMessage(WsSession session, Byte[] msg, int offset, int length) throws Exception {}

    @Override
    public void onError(WsSession session, Throwable throwable) throws Exception {}
  }

Idea 2

  /**
   * Usage: `app.ws("/my/websocket", Websocket.of(new MyWobsocketHandlers()))`
   *
   * `class MyWebsicketHandlers implements WsHandlers { ... }`
   */
  private static final class Websocket implements Consumer<WsHandler> {

    private final WsHandlers delegate;

    private Websocket(WsHandlers delegate) {
      this.delegate = delegate;
    }

    @Override
    public void accept(WsHandler t) {
      t.onConnect(delegate::onConnect);
      t.onMessage(delegate::onMessage);
      /* .. */
    }

    public static interface WsHandlers {
      public abstract void onConnect(WsSession session) throws Exception;
      public abstract void onMessage(WsSession session, String msg);
      /* .. */  
    }

    public static Websocket of(WsHandlers handlers) {
      return new BaseWsHandler(handlers);
    }

  }

#514

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
ernestas2kcommented, Mar 31, 2019

@dherges Actually I like your as well as @tipsy approaches. If you still wish to have class that overrides methods it needs, you could quickly create helper class in your project:

// copy paste this class into your project
class WsHandlerBase {

    //@formatter:off
    protected void onConnect(WsConnectContext ctx) {}
    protected void onMessage(WsMessageContext ctx) {}
    protected void onBinaryMessage(WsBinaryMessageContext ctx) {}
    protected void onClose(WsCloseContext ctx) {}
    protected void onError(WsErrorContext ctx) {}
    //@formatter:on

    public final Consumer<WsHandler> build() {
        return ws -> {
            ws.onConnect(this::onConnect);
            ws.onMessage(this::onMessage);
            ws.onBinaryMessage(this::onBinaryMessage);
            ws.onClose(this::onClose);
            ws.onError(this::onError);
        };
    }
}

// your implementation the way you wanted
class MyWsHandler extends WsHandlerBase {

    @Override
    public void onConnect(WsConnectContext ctx) {
        System.out.println("connected");
    }

    @Override
    public void onMessage(WsMessageContext ctx) {
        ctx.send("echo:" + ctx.message());
    }

}
// usage
public class WebSocketsTest {
    public static void main(String[] args) {
        Javalin app = Javalin.create().enableDebugLogging().port(7070);
        app.ws("/test", new MyWsHandler().build());
        app.start();
    }
}
0reactions
tipsycommented, Mar 31, 2019

I see! You could also do:

app.ws("/websocket", new WsClass()::handle);

...

class WsClass {

    public void handle(WsHandler ws) {
        ws.onConnect(ctx -> {
            System.out.println("Connected");
            ctx.send("[MESSAGE FROM SERVER] Connection established");
        });
        ws.onMessage(ctx -> {
            System.out.println("Received: " + ctx.message());
            ctx.send("[MESSAGE FROM SERVER] Echo: " + ctx.message());
        });
        ws.onClose(ctx -> {
            System.out.println("Closed");
        });
        ws.onError(ctx -> {
            System.out.println("Errored");
        });
    }

}

Is a new class really necessary? 🤔

Read more comments on GitHub >

github_iconTop Results From Across the Web

A Guide to the Java API for WebSocket - Baeldung
WebSocket provides an alternative to the limitation of efficient communication between the server and the web browser by providing ...
Read more >
Creating AsyncAPI for WebSocket API - Step by Step
First, provide some basic information that every good AsyncAPI file should have: What AsyncAPI version do you use? What is the name of...
Read more >
WebSockets With Spring, Part 1: HTTP and WebSocket
The API provides the close method to close the connection. The method has an optional status code and an optional human-readable reason. Once ......
Read more >
JSR 356, Java API for WebSocket - Oracle
JSR 356, Java API for WebSocket, specifies the API that Java developers can use when they want to integrate WebSockets into their applications—both...
Read more >
WebSockets - Send & Receive Messages - Tutorialspoint
It is a lightweight format for transferring human-readable data between the computers. The structure of JSON consists of key-value pairs. Example. { name:...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found