269. WebSocket

The HTTP Client supports the WebSocket protocol. In API terms, the core of the implementation is the java.net.http.WebSocket interface. This interface exposes a suite of methods for handling WebSocket communication.

Building a WebSocket instance asynchronously can be accomplished via HttpClient.newWebSocketBuilder().buildAsync().

For example, we can connect to the well known Meetup RSVP WebSocket endpoint (ws://stream.meetup.com/2/rsvps), as follows:

HttpClient client = HttpClient.newHttpClient();

WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create("ws://stream.meetup.com/2/rsvps"),
wsListener).get(10, TimeUnit.SECONDS);

By its nature, the WebSocket protocol is bidirectional. In order to send data, we can rely on sendText(), sendBinary(), sendPing(), and sendPong(). The Meetup RSVP doesn't process the messages that we send but, just for fun, we can send a text message, as follows:

webSocket.sendText("I am an Meetup RSVP fan", true);

The boolean argument is used to mark the end of the message. If this invocation doesn't complete, the message passes false.

To close the connection, we need to use sendClose(), as follows:

webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "ok");

Finally, we need to write the WebSocket.Listener that will process the incoming messages. This is an interface that contains a bunch of methods with default implementations. The following code simply overrides onOpen(), onText(), and onClose(). Gluing the WebSocket listener and the preceding code will result in the following application:

public class Main {

public static void main(String[] args) throws
InterruptedException, ExecutionException, TimeoutException {

Listener wsListener = new Listener() {

@Override
public CompletionStage<?> onText(WebSocket webSocket,
CharSequence data, boolean last) {
System.out.println("Received data: " + data);

return Listener.super.onText(webSocket, data, last);
}

@Override
public void onOpen(WebSocket webSocket) {
System.out.println("Connection is open ...");
Listener.super.onOpen(webSocket);
}

@Override
public CompletionStage<? > onClose(WebSocket webSocket,
int statusCode, String reason) {
System.out.println("Closing connection: " +
statusCode + " " + reason);

return Listener.super.onClose(webSocket, statusCode, reason);
}
};

HttpClient client = HttpClient.newHttpClient();

WebSocket webSocket = client.newWebSocketBuilder()
.buildAsync(URI.create(
"ws://stream.meetup.com/2/rsvps"), wsListener)
.get(10, TimeUnit.SECONDS);

TimeUnit.SECONDS.sleep(10);

webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "ok");
}
}

This application will run for 10 seconds and will produce output similar to the following:

Connection is open ...

Received data: {"visibility":"public","response":"yes","guests":0,"member":{"member_id":267133566,"photo":"https://secure.meetupstatic.com/photos/member/8/7/8/a/thumb_282154698.jpeg","member_name":"SANDRA MARTINEZ"},"rsvp_id":1781366945...

Received data: {"visibility":"public","response":"yes","guests":1,"member":{"member_id":51797722,...
...

After 10 seconds, the application is disconnected from the WebSocket endpoint.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset