Saturday 9 August 2014

websocket : Encoding the data

A Websocket can use an Encoder to convert the object to text and send it back to the client often, XML or JSON format.

public class Employee {
    String firstName;
    String lastName;
    int age;
    
    Employee(String firstName, String lastName, int age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
}

import com.google.gson.Gson;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
 
public class MessageDecoder implements Decoder.Text<Employee> {
    @Override
    public Employee decode(String s) {
        System.out.println("Incoming JSON " + s);
        Gson gson = new Gson();
        Employee emp = gson.fromJson(s, Employee.class);
        return emp;
    }

    @Override
    public boolean willDecode(String s) {
        return (s != null);
    }

    @Override
    public void init(EndpointConfig endpointConfig) {
        // do nothing.
    }

    @Override
    public void destroy() {
        // do nothing.
    }
}

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import com.google.gson.Gson;

public class MessageEncoder implements Encoder.Text<Employee>{

    @Override
    public String encode(Employee emp) throws EncodeException {
        Gson gson = new Gson();
        System.out.println("Converting employee object to json format");
 String json = gson.toJson(emp);
        return json;
    }

    @Override
    public void init(EndpointConfig config) {
        
    }

    @Override
    public void destroy() {
      
    }
    
}

import java.io.IOException;
import javax.websocket.EncodeException;
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(value = "/endpoint", 
decoders = { MessageDecoder.class},
encoders = {MessageEncoder.class})
public class EmployeeProcess {
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) {
        }
    }
 
    /* Notified when the client sends message to server */
    @OnMessage
    public void onMessage(Employee emp, Session session) throws IOException, EncodeException{      
       RemoteEndpoint.Basic basic = session.getBasicRemote();
       basic.sendObject(emp);
    }
 
   /* 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>
            <textarea id="messageinput" rows="4" cols="50" name="messageinput" ></textarea>
        </div>
        <div>
            <button type="button" onclick="openSocket();" >Open</button>
            <button type="button" onclick="send();" >send data</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