Saturday 9 August 2014

Sending Messages to client

Websocket endpoints can send both text and binary messages, ping and pong frames.

It is a 3 step process
Step 1: Get the session object. Session object is available as a parameter to the life cycle methods of endpoint.

Step 2: Get the RemoteEndpoint object from the session object obtained in step 1. The Session.getBasicRemote method and the Session.getAsyncRemote method return RemoteEndpoint.Basic and RemoteEndpoint.Async objects respectively. RemoteEndpoint.Async interface provides nonblocking methods to send messages.

Step 3: Use the RemoteEndpoint object to send messages to the peer.

Methods in RemoteEndpoint.Basic to send message to client
Method Description
sendBinary(ByteBuffer data) Send a binary message, returning when all of the message has been transmitted.
sendBinary(ByteBuffer partialByte, boolean isLast) Send a binary message in parts, blocking until all of the message has been transmitted. Non-final parts are sent with isLast set to false. The final piece must be sent with isLast set to true.
sendObject(Object data) Sends a custom developer object, blocking until it has been transmitted
sendText(String text) Send a text message, blocking until all of the message has been transmitted.
sendText(String partialMessage, boolean isLast) Send a text message in parts, blocking until all of the message has been transmitted.Non-final parts are sent with isLast set to false. The final piece must be sent with isLast set to true.

Methods in RemoteEndpoint.Async to send message to client
Method Description
sendBinary(ByteBuffer data) Initiates the asynchronous transmission of a binary message. This method returns before the message is transmitted.
sendBinary(ByteBuffer data, SendHandler handler) Initiates the asynchronous transmission of a binary message. This method returns before the message is transmitted. The handler will be notified of progress.
sendObject(Object data) Initiates the asynchronous transmission of a custom developer object.
sendObject(Object data, SendHandler handler) Initiates the asynchronous transmission of a custom developer object. The handler will be notified of progress.
sendText(String text) Initiates the asynchronous transmission of a text message. This method returns before the message is transmitted.
sendText(String text, SendHandler handler) Initiates the asynchronous transmission of a text message. This method returns before the message is transmitted. The handler will be notified of progress.

RemoteEndpoint.Basic, RemoteEndpoint.Async interfaces extends RemoteEndpoint interface which provide method to send ping and pong frames.

Methods in RemoteEndpoint to send message to client
Method Description
sendPing(ByteBuffer applicationData) Send a Ping message containing the given application data to the remote endpoint.
sendPong(ByteBuffer applicationData) Allows the developer to send an unsolicited Pong message containing the given application data in order to serve as a unidirectional heartbeat for the session.

For Example, will write an Application, where client sends a number to server and server calculates probable prime specific to this number and send the result back to client.

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 {
    
    /* 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();
        
        String s = ProbablePrime.getProbablePrime(message);
        try {
            basic.sendText("Probable prime is " + s);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
 
   /* 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