[Detailed Tutorial] Building a HTTP server with WebSocket support using QBit (very easy)

fadihub edited this page Mar 23, 2015 · 2 revisions

##overview

WebSocket is designed to be implemented in web browsers and web servers, it can facilitate live content; this is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. WebSocket is very fast.

Building a HTTP server with WebSocket support using QBit - very easy

This wiki will walk you through the process of building an HTTP server with WebSocket support, we will show how easy it is to build with QBit.

What you will build

You will build a HTTP server with WebSocket support, and you will be able to test it by sending a couple of text messages to it, When you run it you will get the following:

ECHO Hi mom
ECHO Hello World!

How to complete this guide

In order to complete this example successfully you will need the following installed on your machine:

Now that your machine is all ready let's get started:

https://github.com/fadihub/echo-websocket.git

Once this is done you can test the service, let's first explain the process:

First step is to create a HTTP server, this is done as follows:

 /* Create an HTTP server. */
        HttpServer httpServer = httpServerBuilder()
                .setPort(8080).build();

then to enable WebSocket support using java 8 Lambda expression, do the following:

  /* Setup WebSocket Server support. */
        httpServer.setWebSocketOnOpenConsumer(webSocket -> {
            webSocket.setTextMessageConsumer(message -> {
                webSocket.sendText("ECHO " + message);

and finally start the server up:

/* Start the server. */
        httpServer.start();

This is it, you are done, very simple.

In order to test it; send/receive messages to the WebSocket server we need a client. First to create, start a HTTP client, and set its port number to 8080 do the following:

/* Setup an httpClient. */
        HttpClient httpClient = httpClientBuilder()
                .setHost("localhost").setPort(8080).build();
        httpClient.start();

To add WebSocket support to it do the following:

/* Setup the client websocket. */
        WebSocket webSocket = httpClient
                .createWebSocket("/websocket/rocket");

        webSocket.setTextMessageConsumer(message -> {
            System.out.println(message);
        });
        webSocket.openAndWait();

Now the WebSocket server is ready to receive messages, here we will send a couple of messages:

 /* Send some messages. */
        webSocket.sendText("Hi mom");

        webSocket.sendText("Hello World!");

and finally close the server and the client:

  webSocket.close();
  httpClient.stop();
  httpServer.stop();

We are done and ready to test.

EchoWebSocket.java Listing

~/src/main/java/io.advantageous.qbit.example.echowebsocket/EchoWebSocket

/*
 * Copyright (c) 2015. Rick Hightower, Geoff Chandler
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * QBit - The Microservice lib for Java : JSON, WebSocket, REST. Be The Web!
 */

package io.advantageous.qbit.example.echowebsocket;

import io.advantageous.qbit.http.client.HttpClient;
import io.advantageous.qbit.http.server.HttpServer;
import io.advantageous.qbit.http.websocket.WebSocket;
import io.advantageous.boon.core.Sys;

import static io.advantageous.qbit.http.client.HttpClientBuilder.httpClientBuilder;
import static io.advantageous.qbit.http.server.HttpServerBuilder.httpServerBuilder;

/**
 * Created by rhightower on 2/16/15.
 */
public class EchoWebSocket {


    public static void main(String... args) {


        /* Create an HTTP server. */
        HttpServer httpServer = httpServerBuilder()
                .setPort(8080).build();

        /* Setup WebSocket Server support. */
        httpServer.setWebSocketOnOpenConsumer(webSocket -> {
            webSocket.setTextMessageConsumer(message -> {
                webSocket.sendText("ECHO " + message);
            });
        });

        /* Start the server. */
        httpServer.start();

        /** CLIENT. */

        /* Setup an httpClient. */
        HttpClient httpClient = httpClientBuilder()
                .setHost("localhost").setPort(8080).build();
        httpClient.start();

        /* Setup the client websocket. */
        WebSocket webSocket = httpClient
                .createWebSocket("/websocket/rocket");

        webSocket.setTextMessageConsumer(message -> {
            System.out.println(message);
        });
        webSocket.openAndWait();

        /* Send some messages. */
        webSocket.sendText("Hi mom");

        webSocket.sendText("Hello World!");


        Sys.sleep(1000);
        webSocket.close();
        httpClient.stop();
        httpServer.stop();
    }

}

build.gradle

group = 'io.advantageous.qbit'
apply plugin: 'idea'
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'application'

sourceCompatibility = 1.8
version = '1.0'


repositories {
    mavenLocal()
    mavenCentral()
}

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

mainClassName = "io.advantageous.qbit.example.echowebsocket.EchoWebSocket"



    dependencies {
        compile group: 'io.advantageous.qbit', name: 'qbit-vertx', version: '0.7.2'


        compile "org.slf4j:slf4j-api:[1.7,1.8)"
        compile 'ch.qos.logback:logback-classic:1.1.2'

        testCompile group: 'junit', name: 'junit', version: '4.10'
}




    idea {
        project {
            jdkName = '1.8'
            languageLevel = '1.8'
        }

    }

Test The Service

With your terminal cd echo-websocket

then gradle clean build and finally gradle run you should get the following:

ECHO Hi mom
ECHO Hello World!

Summary

As you can see building a WebSocket server is very simple with QBit. You have built and tested a HTTP server with WebSocket support using QBit, see you in the next tutorial!

Tutorials

__

Docs

Getting Started

Basics

Concepts

REST

Callbacks and Reactor

Event Bus

Advanced

Integration

QBit case studies

QBit 2 Roadmap

-- Related Projects

Kafka training, Kafka consulting, Cassandra training, Cassandra consulting, Spark training, Spark consulting

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.