Saturday, 9 August 2014

Annotated server endpoint

You can create server endpoint using @ServerEndpoint annotation. It is simpler than the equivalent programmatic endpoint. It is deployed automatically with the application to the relative path defined in the ServerEndpoint annotation.

Below endpoint lifecycle Annotations available with javax.websocket package
Annotation Description
OnClose Method annotated with OnClose is called when a web socket session is closing.
OnError Method annotated with OnErro is called in order to handle errors.
OnMessage This method level annotation can be used to make a Java method receive incoming web socket messages.
OnOpen Method annotated with OnOpen is called when a new web socket session is open

socket.html
<!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();" >Send</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>

EchoServer.java
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;
 
@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){
        System.out.println("Message from " + session.getId() + ": " + message);
        try {
            session.getBasicRemote().sendText(message);
        } 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");
    }
}

Run socket.html

It opens window like above, If you click 'open' it opens a new connection, if there is no connection established. Button 'close' is used to close the connection.
type some information and press 'send' it sends the information to the server.

I just opened connection, typed 'Hello Server' and send the information to server and closes the connection.


You can see below messages in server console.
Info: cef11ce7-2f9d-4d58-ab2a-179f83916c7e has opened a connection
Info: Message from cef11ce7-2f9d-4d58-ab2a-179f83916c7e: Hello Server
Info: Session cef11ce7-2f9d-4d58-ab2a-179f83916c7e has ended




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment