Programming Model

This chapter gives you a quick overview of programming models available supported by the Java WebSocket API

You'll see extensive coverage of these programming models through topics explored in other chapters

There are two programming models

  • Annotation based (declarative) and

  • Programmatic (using inheritance)

Annotation based model

This model makes use of class and method level annotations. These are used to denote classes as server or client end points and designate their methods as target of callbacks (connection opened or closed, message received, error) initiated by the WebSocket container

Here is a snippet - for now, just notice the use of annotations

//annotated endpoint

@ServerEndpoint("/test/")
public class AnnotatedEndpoint {
    @OnOpen
    public void onOpenCallback(Session s, EndpointConfig ec){
      ...
    }
    @OnMessage
    public void OnMessageCallback(String messageFromClient){
      ...
    }
    @OnClose
    public void onCloseCallback(Session s, CloseReason cr){
      ...
    }
    @OnError
    public void onErrorCallback(Session s, Throwable t){
      ...
    }
}

Programmatic API based model

The Programmatic API revolves around extending the javax.websocket.Endpoint class. If you decide to adopt this model, you'll need to make use of the following interfaces and classes. Here is a preview

T is the generic type parameter representing the actual object type of the message

//programmatic endpoint

public class ProgrammaticEndpoint extends Endpoint {
    @Override
    public onOpen(Session session, EndpointConfig config) {
      session.addMessageHandler((String s) -> System.out.println("got msg "+ s));
    ....
    }
}

Differences

Now that you have a basic idea of these models, the differences might be obvious. The table below serves as a quick reference

Up next

How can you use the API to Send Messages to connected peers ? This topic will be explored in the next chapter

Last updated