Server WebSocket Clients, with Jetty

May 3rd, 2013

Previously I discussed how to write a Server which uses a persistent WebSocket Client, using the Netty framework to make things go.  Netty is configured through establishing a Channel Pipeline, which is great if you need a very flexible system for handling network input and output.  For most projects however, this sort of power can be overkill.

Jetty

Jetty, among other great things, contains a WebSocketClient implementation.  Getting this up and running is very simple: you’ll need a WebSocketClientFactory, where you can configure various settings, and a WebSocketClient which also has a bunch of settings to flip around to meet your needs.  Once you have those, you’ll need a class that implements WebSocket.OnTextMessage …and you’re pretty much done at this point. 

The code for sending and receiving messages becomes equally simple:

@Override

public void send(Message message) {

    // a message is going out!

    String data = null;

    try {

        data = messageToString(message);

        connection.sendMessage(data);

    } catch (Exception e) {

        logger.error("Failed to send message! " + data, e);

    }

}

 

@Override

public void onMessage(String data) {

    // a message is coming in!

    logger.debug("message received: {}", data);

    try {

        Message message = stringToMessage(data);

        handleMessage(message);

    } catch (IOException e) {

        logger.error("Failed to parse incoming message! " + data, e);

    }

}

 

The complete code for this example can be found at

https://github.com/trasa/WebSocketClientServer/tree/jettyclient

Comments are closed.