Saturday 9 August 2014

Broadcasting messages to all the clients

Session class provides getSession() method, it returns set of all the open web socket sessions.

import java.math.*;

public class ProbablePrime {
    static String getProbablePrime(String num){
        BigInteger b1 = new BigInteger(num);
        return b1.nextProbablePrime().toString();
    }
}

import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.*;
 
@ServerEndpoint("/endpoint") 
public class EchoServer {
    
    /* Notified when a new web socket session is open. */
    @OnOpen
    public void onOpen(Session session){
        System.out.println(session.getId() + " has opened a connection"); 
        try {
            session.getBasicRemote().sendText("Connection Established");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 
    /* Notified when the client sends message to server */
    @OnMessage
    public void onMessage(String message, Session session){
        Set<Session> sessions = session.getOpenSessions();
        
        String s = ProbablePrime.getProbablePrime(message);
        
        for(Session mySession :  sessions){
            if(mySession.isOpen()){
                try {
                    mySession.getBasicRemote().sendText("Probable prime is " + s);
                } 
                catch (IOException ex) {
                }
            }
        }
    }
 
   /* notified when the user closes connection */
    @OnClose
    public void onClose(Session session){
        System.out.println("Session " +session.getId()+" has ended");
    }
}

<!DOCTYPE html>
<html>
    <head>
        <title>Echo Chamber</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
       
        <div>
            <input type="text" id="messageinput"/>
        </div>
        <div>
            <button type="button" onclick="openSocket();" >Open</button>
            <button type="button" onclick="send();" >Get Probable Prime</button>
            <button type="button" onclick="closeSocket();" >Close</button>
        </div>
        <!-- Server responses get written here -->
        <div id="messages"></div>
       
        <!-- Java script for websockets -->
        <script type="text/javascript">
                       
            var connection;
            var messages = document.getElementById("messages");
           
           
            function openSocket(){
                // Ensures only one connection is open at a time
                if(connection !== undefined && connection.readyState !== connection.CLOSED){
                   writeResponse("WebSocket is already opened.");
                    return;
                }
                // Create a new instance of the websocket
                connection = new WebSocket("ws://localhost:8080/websockets/endpoint");
                 
                /* Binds the listeners to socket */
                connection.onopen = function(event){
                    if(event.data === undefined)
                        return;
 
                    writeResponse(event.data);
                };
 
                connection.onmessage = function(event){
                    writeResponse(event.data);
                };
 
                connection.onclose = function(event){
                    writeResponse("Connection closed");
                };
                
            }
           
            /* Send messgae to the server */
            function send(){
                var text = document.getElementById("messageinput").value;
                connection.send(text);
            }
           
           /* Close the socket */
            function closeSocket(){
                connection.close();
            }
 
            function writeResponse(text){
                messages.innerHTML += "<br/>" + text;
            }
           
        </script>
       
    </body>
</html>


As you observe the above image, there are teo connection,one from mozilla, and other from chrome, but whenever client request for probable prime, then server broadcast the response to all the open connections.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment