Thursday

javax.websocket example

I will show an example of Web Socket. I'll use a Javascript WebSocket API  to reconnect periodically to the server.

Server Side:
1. WebSocketDecoder.java
import java.io.IOException;
import java.io.Reader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

public class WebSocketDecoder implements Decoder.TextStream<JsonObject> {

        @Override
        public void init(EndpointConfig config) {}

        @Override
        public void destroy() {}

       @Override
       public JsonObject decode(Reader reader) throws DecodeException, IOException {
         try (JsonReader jReader = Json.createReader(reader)) {
               return jReader.readObject();
        }
       }

}

2. WebSocketEncoder.java

import java.io.IOException;
import java.io.Writer;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

public class WebSocketEncoder implements Encoder.TextStream<JsonObject> {

    @Override
    public void init(EndpointConfig config) {}

    @Override
    public void encode(JsonObject jsonLoad, Writer writer) throws EncodeException, IOException {
        try (JsonWriter jsonWriter = Json.createWriter(writer)) {
            jsonWriter.writeObject(jsonLoad);
        }
    }

    @Override
    public void destroy() {}
}

3. WebSocket.java
import java.io.IOException;
import java.util.HashMap;

import javax.faces.bean.ApplicationScoped;
import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ApplicationScoped
@ServerEndpoint(value = "/ltmc/{username}", encoders = {WebSocketEncoder.class}, decoders = {WebSocketDecoder.class})
public class WebSocket {

    private static HashMap<String, Session> users = new HashMap<>();

    @OnOpen
    public void onOpen(Session session,  @PathParam("username") String username) {
       users.put(username, session);
    }

    @OnClose
    public void onClose(Session client) {
       users.remove(client);
    }

    //If the client send a message, you can procces it in this method.
    @OnMessage
    public void onMessage(JsonObject request, Session client) {
       //We're sending client message, to the client again.
       client.getBasicRemote().sendObject(request);
    }

    @OnError
    public void onError(Session client, Throwable t) {
       //log the error detail
    }

    //You can call this method from other classes.
    //It will send a json object message to the client. The message will be caught from 'onmessage' method on client in notification.socket.js
    public void sendNotification(String username) throws IOException, EncodeException {
       Session client = users.get(username);

       if(client != null && client.isOpen()) {
           JsonObject event = Json.createObjectBuilder()
                    .add("user","Less Talk More Code")
                    .build();
           client.getBasicRemote().sendObject(event);
           
       } else {
             //log that user can't find
       }
    }
}

Client Side:
1. reconnect.web.socket.js >> you can download from   https://github.com/joewalnes/reconnecting-websocket

2. notification.socket.js
var webSocket;

function initNotificationSocket(){
       var wsUri = url;
       websocket = new ReconnectingWebSocket(wsUri, null, {debug: true, reconnectInterval: 3000});
       websocket.onmessage = function(event) {
             onMessage(event);
       };
       //We're sending message to the server. 
       //This message will be caught in the onmessage method - WebSocket.java
       websocket.send(JSON.stringify({"user":"hello"}));
}

function onMessage(event) {
       var msg = JSON.parse(event.data);
       alert(msg.user );
}

initNotificationSocket();

3. add following codes to your .jsp file.
<script type="text/javascript">
     var url = "ws://" + "server side address:port" + "/ltmc/" + "your dynamic username";
</script>
       
<script type="text/javascript" src="js/reconnect.web.socket.js"></script>
<script type="text/javascript" src="js/notification.socket.js"></script>

No comments:

Post a Comment