Creating a simple Server/Client application using websockets

Introduction

Websockets are a powerful tool for creating real time applications. The websocket protocol runs over TCP . Unlike HTTP, it provides a bi-directional, full-duplex communications channels. Apart from having its own protocol, websocket also has an API which can be used by web applications to open and close connections and to send and receive messages.

Getting started

To illustrate how websockets work, we’re going to create a simple application that allows the user to send text to the server, which in turn will display the message back to the user.

First download the first zip marked as server from jWebSocket Downloads

Make sure JWEBSOCKET_HOME environment variable refers to the jWebSocket root folder then add the following JARs to your class path:

  • JWEBSOCKET_HOME/libs/jWebSocketServer-1.0.jar
  • JWEBSOCKET_HOME/libs/jWebSocketServerAPI-1.0.jar
  • JWEBSOCKET_HOME/libs/jWebSocketCommon-1.0.jar

The server side

import org.jwebsocket.api.WebSocketPacket;
import org.jwebsocket.api.WebSocketServerListener;
import org.jwebsocket.config.JWebSocketConfig;
import org.jwebsocket.factory.JWebSocketFactory;
import org.jwebsocket.instance.JWebSocketInstance;
import org.jwebsocket.kit.WebSocketServerEvent;
import org.jwebsocket.server.TokenServer;

class Listener implements WebSocketServerListener{

    @Override
    public void processClosed(WebSocketServerEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void processOpened(WebSocketServerEvent arg0) {
        // TODO Auto-generated method stub

        System.out.println("Connection opened");
    }

    @Override
    public void processPacket(WebSocketServerEvent event, WebSocketPacket packet) {
        // TODO Auto-generated method stub

        packet.setString("The client says:"+ packet.getString());
        event.sendPacket(packet);

    }

}

public class EchoServer {

public static void main(String[] args){

        JWebSocketFactory.printCopyrightToConsole();
        JWebSocketConfig.initForConsoleApp(new String[]{});
        JWebSocketFactory.start();
        TokenServer server = (TokenServer) JWebSocketFactory.getServer("ts0");
        if(server!=null)
            server.addListener(new Listener());
        while (JWebSocketInstance.getStatus()!=JWebSocketInstance.SHUTTING_DOWN)
            try {
                Thread.sleep(250);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }

}

processOpened  is called , as its names suggests, when a connection is opened.
processPacket  is called whenever a client sends a message to the server.

The Client side

testsocket.html

<!DOCTYPE html>
<html>
    <head>
        <title> Application test </title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <script src="testsocket.js" type="text/javascript"></script>
    </head>

    <body id="body">
        <div id="header"><strong>Application test</strong></div>

                    <p>Have fun using websockets! </p>
                    <br/>

                    <table>
                        <tr>
                            <td><textarea id="chatMessage" rows="3" cols="75" placeholder=""></textarea></td>
                            <td><input type="button" value="Send" name="sendB" onclick="sendMessage(chatMessage.value)" /></td>
                        </tr>

                        <tr>
                            <td><textarea readonly id="display" rows="3" cols="75" placeholder="" value=""></textarea></td>

                        </tr>

                    </table>

    </body>
</html>

testsocket.js

var connection = new WebSocket('ws://localhost:8787', 'json');

connection.onopen = function () {
  console.log('Connection Opened');

};
connection.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};
connection.onmessage = function (e) {
  var textarea = document.getElementById("display");
  textarea.value = e.data;
};
function sendMessage(msg){
  connection.send(msg);
}

onopen event is fired when the connection is established.
onclose is triggred when the connection is closed.
onmessage event is fired whenever the client receives a message from the server.
onerror is fired whenever an error occurs.
the method send is used for sending messages to the server.

Demos

Don’t forget to check out some interesting demo applications using websocket technology here.

2 thoughts on “Creating a simple Server/Client application using websockets

Leave a comment