HTML5 web sockets provides stable connectivity to servers. By using these web sockets we can setup a stable connection between browser and sever, and then we can send or receive messages.

Like shown in below image, users send and receive messages on real time


Observe below GIF, One is chrome and another is firefox, Whatever we type in chrome, that will be displayed in firefox.

Lets write java program for sharing editor

Java Program

To run below program, you need add java_websocket dependency. Here it is the maven dependency xml.
<dependency>
  <groupId>org.java-websocket</groupId>
  <artifactId>Java-WebSocket</artifactId>
  <version>1.3.0</version>
</dependency>

Once you install the above dependencies, run below program
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Set;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

public class App extends WebSocketServer {

    private static int TCP_PORT = 4444;
    private String value = "";

    private Set<WebSocket> conns;

    public App() {
        super(new InetSocketAddress(TCP_PORT));
        conns = new HashSet<WebSocket>();
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        conn.send(value);
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        conns.remove(conn);
        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Message from client: " + message);
        value = message;
        for (WebSocket sock : conns) {
            sock.send(message);
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }
        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }
    
    public static void main(String[] args) {
        new App().start();
    }
}

HTML Code 

This code contains textarea element. Whatever user types in that textarea, it will be sent to java web socket server. Java server will send that message to all its connections. That is how one user's text will be shown to all users. 
<!DOCTYPE html>
<html>
    <head>
    <style>
        .layout {
            width:800px;
            margin:auto;
        }
        
        textarea {
            max-width:800px;
            width:80%;
            border:1px solid #ccc;
            font-size:14px;
            height:400px;
        }
    </style>
    <script>
        var ws = new WebSocket("ws://127.0.0.1:4444/");
        var elm = document.getElementById('myTextArea');
    
        ws.onopen = function() {
            console.log("Opened!");
        };
    
        ws.onmessage = function (evt) {
            myTextArea.value = evt.data;
        };
    
        ws.onclose = function() {
            alert("Closed!");
        };
    
        ws.onerror = function(err) {
            alert("Error: " + err);
        };
    
        function share(event) {
            ws.send(event.target.value);
        }
    </script>
    </head>
    <body>
       <div class="layout">
        <h1>Sharing editor</h1> 
        <textarea id="myTextArea" onkeyup="share(event)" rows="100" cols="50"></textarea>
       </div>
    </body>
</html>

5 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts