Saturday 9 August 2014

websocket : Maintain client State

Websocket container creates an instance of the endpoint class for every connection, so by using instance variables we can maintain the state of the connection. To store the information common to all clients you can use static variables.

In addition to this, Session class provides getUserProperties() method, While the session is open, this method returns a Map that the developer may use to store application specific information relating to this session instance. Developer can access the information stored any time between opening of the session and during the onClose() method.

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.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
 
@ServerEndpoint("/endpoint") 
public class EchoServer {
    
    String s;
    
    /* 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){
        RemoteEndpoint.Basic basic = session.getBasicRemote(); 
        s = ProbablePrime.getProbablePrime(message);
        
        try {
            basic.sendText("Probable prime is " + s);
            basic.sendText("Previous input is " + session.getUserProperties().get("prev"));
        } catch (IOException ex) {
        }
        session.getUserProperties().put("prev", message);
    }
 
   /* 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>

Output




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment