Saturday, 9 August 2014

Simple Websocket Application

Before dig into further, will try simple websocket example. We can write a simple application in combination of HTML, Javascript, javax.websocket API.

Websocket support using Javascript
will discuss, how to create a websocket object, How to send/receive data to/from the server.

Creating a WebSocket object
var connection = new WebSocket('url', protocols);
creation ob websocket object automatically attempt to open the connection to the server.

Example
connection = new WebSocket("ws://localhost:8080/websockets/echo");

Second parameter 'protocols' is optional. Protocols specify either a single protocol string or an array of protocol strings.

Example
var connection = new WebSocket("ws://localhost:8080/websockets/echo", ['chat', 'super-awesome-chat']);

If your connection is accepted and established by the server, then an onopen event is fired on the client’s side. You can handle it like below.

connection.onopen = function(event){
 if(event.data === undefined)
           return;
        //Do processing with event.data
};

If the connection is refused by the server, or for some other reason is closed, then the onclose event is fired.

connection.onclose = function(event){
       writeResponse("Connection closed");
     };

You can close the connection explicitly by calling close method on connection object.

connection.close()

Send and Receiving message to server
sending data to the server is pretty straight forward. You can send the data to the server by calling the send() on connection object.

    connection.send("Hello Server");

Whenever client receives a message from a server then, it raises the onmessage event for you to handle.

connection.onmessage = function(event){
  //Process event.data
              };

How to send JSON object to the server
If you want to send JSON object to server, then that object should be serialized to a string like below.

var message = {
'name': 'Krishna',
'comment': 'Learning websockets is pretty simple'
};
connection.send(JSON.stringify(message));

This is the basic introduction to javascript websocket support.

Websocket using java
We have to create web socket endpoint, to which client websocket connect to. It can be achieved in two ways, one by extending Endpoint class and other by using ServerEndpoint annotation. @ServerEndpoint gives the relative name for the end point, it is accessed via 'ws://localhost:8080/websockets/echo'

I am going to create websocket application using annotation way.

Below procedure shows step by step, how to deploy websocket application using Netbeans.

1. Open new project and select 'Java Web' from categories section and select 'Web Application' from projects section. Press next


2. Give the project name as 'websockets' and press next.

3. Select the server (I am using glassfish), Select javaEE version as 7 or above and press next.

4. No need to select anything, press Finish.


5. Create a new HTML file 'socket.html'


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>

6. Create a Websocket endpoint (EchoServer).  





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");
    }
}

7. 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