Creating a simple Server/Client application using websockets


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{

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


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

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

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

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



public class EchoServer {

public static void main(String[] args){

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



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


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

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

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

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

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





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 =;
function sendMessage(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.


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 Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s