/java/

Web Socket. Simple example. Json message.

2015-05-31 17:55:14

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');

    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.dto.MessageDto;
import btbw.dto.MessageDtoDecoder;
import btbw.dto.MessageDtoEncoder;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint(
        value = "/websocket/json",
        encoders = {MessageDtoEncoder.class},
        decoders = {MessageDtoDecoder.class}
)
public class JsonWebSocket {

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

        System.out.println("Received. Subject: " + message.getSubject() + " Received: " + message.getContent());

        session.getBasicRemote().sendObject(new MessageDto("Dto: Michał", "Btbw"));

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

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

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

Encoder & Decoder. String to Dto, Dto to String

MessageDto

package btbw.dto;

public class MessageDto {

    private String subject;
    private String content;

    public MessageDto() {
    }

    public MessageDto(String subject, String content) {
        this.subject = subject;
        this.content = content;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

MessageDtoDecoder

package btbw.dto;

import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import java.io.StringReader;

public class MessageDtoDecoder implements Decoder.Text

<messagedto> {

    @Override
    public MessageDto decode(String jsonMessage) throws DecodeException {

        JsonObject jsonObject = Json
                .createReader(new StringReader(jsonMessage)).readObject();
        MessageDto message = new MessageDto();
        message.setSubject(jsonObject.getString("subject"));
        message.setContent(jsonObject.getString("content"));
        return message;

    }

    @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 ec) {
        System.out.println("MessageDtoDecoder -init method called");
    }

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

}

MessageDtoEncoder

package btbw.dto;

import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

public class MessageDtoEncoder implements Encoder.Text<messagedto> {

    @Override
    public String encode(MessageDto message) throws EncodeException {

        JsonObject jsonObject = Json.createObjectBuilder()
                .add("subject", message.getSubject())
                .add("content", message.getContent()).build();
        return jsonObject.toString();

    }

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

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

}