/java/

Web Socket. Simple example. Json Map message. More Generic way.

2015-05-31 18:57:37

GitHub

frontend: Html 5 WebSocket

<!DOCTYPE html>

<html>
<head>
<title>Web Socket: String Json</title>
</head>
<body>
<div>
<input onclick='"start()"/' type='"submit"' value='"Start"'/>
</div>
<div id='"messages"'></div>
<script type='"text/javascript"'>

    var webSocket = new WebSocket('ws://localhost:8080/app/websocket/json/map');

    webSocket.onerror = function (event) {
        console.log(event);
        alert('Error');
    };

    webSocket.onopen = function (event) {
        console.log(event);
        alert('Connection established');
    };

    webSocket.onmessage = function (event) {
        console.log(event);
        var json = JSON.parse(event.data);
        document.getElementById('messages').innerHTML += '<br />' + event.data;
    };

    function start() {
        var json = {
            'subject': &quot;Michał S&quot;,
            'content': &quot;Btbw 2015&quot;
        };
        webSocket.send(JSON.stringify(json));
        return false;
    }
</script>
</body>
</html>

backend: Jee, javax.websocket

package btbw.socket;

import btbw.map.MessageMapDecoder;
import btbw.map.MessageMapEncoder;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint(
        value = "/websocket/json/map",
        encoders = {MessageMapEncoder.class},
        decoders = {MessageMapDecoder.class}
)
public class JsonMapWebSocket {

    @OnMessage
    public void onMessage(Map message, Session session) throws IOException, InterruptedException, EncodeException {

        session.getBasicRemote().sendObject(getRow("Map: Michał", "Btbw"));

        for (int i = 0; i &lt; 3; i++) {
            Thread.sleep(2000);
            session.getBasicRemote().sendObject(getRow("Map: Michał", "Btbw " + i));
        }
    }

    @OnOpen
    public void onOpen() {
        System.out.println("Client connected");
    }

    @OnClose
    public void onClose() {
        System.out.println("Connection closed");
    }

    private Map

<string, string=""> getRow(String key, String value) {
        HashMap<string, string=""> map = new HashMap&lt;&gt;();
        map.put(key, value);
        return map;
    }
}

Encoder & Decoder. String to Map, Map to String

package btbw.map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import javax.json.Json;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

public class MessageMapDecoder implements Decoder.Text<map> {

    @Override
    public Map decode(String json) throws DecodeException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(json, new TypeReference<hashmap<string, string="">&gt;() {});
        } catch (Exception e) {
            System.out.print("Problem with Decoder: " + e.getMessage());
            return new HashMap();
        }
    }

    @Override
    public boolean willDecode(String jsonMessage) {
        try {
            Json.createReader(new StringReader(jsonMessage)).readObject();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void init(EndpointConfig config) {
        System.out.println("MessageMapDecoder -init method called");
    }

    @Override
    public void destroy() {
        System.out.println("MessageMapDecoder - destroy method called");
    }
}
package btbw.map;

import org.codehaus.jackson.map.ObjectMapper;

import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import java.io.IOException;
import java.util.Map;

public class MessageMapEncoder implements Encoder.Text<map> {

    @Override
    public String encode(Map map) throws EncodeException {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(map);
        } catch (IOException e) {
            System.out.print("Problem with Encoder: " + e.getMessage());
            return "-";
        }
    }

    @Override
    public void init(EndpointConfig config) {
        System.out.println("MessageMapEncoder - init method called");
    }

    @Override
    public void destroy() {
        System.out.println("MessageMapEncoder - destroy method called");
    }
}