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>

21 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
  2. Very useful and interesting content.

    Mask
    Quickbooks Expert
    quickbooks support phone number

    ReplyDelete
  3. It provides stable connectivity to servers!
    yahoo mail sign up new user

    ReplyDelete
  4. If any page has quality posts like yours then I will search for information very quickly. Please donate again
    ludo king

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Thanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this.iot training institutes in chennai | industrial iot training chennai | iot certification chennai | iot training courses in chennai

    ReplyDelete
  7. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Check out : machine learning tution in chennai
    artificial intelligence and machine learning course in chennai
    best training insitute for machine learning

    ReplyDelete
  8. Just seen your Article, it amazed me and surpised me with god thoughts that eveyone will benefit from it. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Thanks
    DedicatedHosting4u.com

    ReplyDelete
  9. Buat kalian pemain pemula atau profesional tentunya membutuhkan teknik yang pas untuk menang dalam permainan AduQ Online
    asikqq
    dewaqq
    sumoqq
    interqq
    pionpoker
    bandar ceme terpercaya
    hobiqq
    paito warna
    forum prediksi

    ReplyDelete
  10. Really informative article.Really looking forward to read more. Really Cool.
    คาสิโนออนไลน์ที่น่าเชื่อถือและมีความเป็นมืออาชีพที่สุดในตอนนี้
    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร สล็อตออนไลน์ กับทางทีมงานของเราเพียงเท่านั้น
    ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสล็อตออนไลน์ >>> Goldenslot
    สนใจร่วมสนุกกับ คาสิโนออนไลน์ คลิ๊กได้เลย
    มีทั้งคาสิโนออนไลน์ หวยออนไลน์ ฟุตบอลออนไลน์ สล็อตออนไลน์ และอื่นๆอีกมากมาย

    ReplyDelete
  11. Great. It is good to constantly coming up with creative ideas. Provides much needed knowledge. goal oriented blog posts and always tried to find creative ways to meet goals.

    Thanks
    Online affiliates

    ReplyDelete
  12. AppVN is a third-party app store for Android. Unlike Google Play, this app store provides you with some unique features, such as the facility to download certain official premium apps for free.
    https://appvn.one
    AppVN
    Appvn APK
    appvn ios
    appvn apk download

    ReplyDelete

  13. Your post is very good. I got to learn a lot from your post. Thank you for sharing your article for us. it is amazing post
    what is seo
    types of seo


    ReplyDelete
  14. This is a fantastic idea! I like it a lot because it's super easy for the audience to see the value of opting in. wonderful and amazing post very use full your post thanks for sharing your article
    Android Application development
    Web application

    ReplyDelete

  15. Get the most advanced Hadoop Course by Professional expert. Just attend a FREE Demo session.
    call us @ 9884412301 | 9600112302
    Hadoop training in chennai | Hadoop training in velachery

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts