czwartek, 15 czerwca 2017

How to add more destinations to SpringBoot WebSocket STOMP app.



This is extension for https://spring.io/guides/gs/messaging-stomp-websocket/ article - you must read it first.

Goal of this version is to add more subscribes and destination for WebSocket.





In original GreetingController was:  

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(100); // simulated delay
        System.out.println("HelloMessage message "+ message.getName());
        return new Greeting("Hello, " + message.getName() + "!");
    }



I added more SubscribeMappings:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    @SubscribeMapping("/helloagain")
    @SendTo("/topic/greetings")
    public Greeting greetingAgain(HelloMessage message) throws Exception {
//        greetingAuto(message);
        broadcastMess(message);
        Thread.sleep(1000); // simulated delay
        System.out.println("HelloMessage again message "+ message.getName());
        return new Greeting("Hello again, " + message.getName() + "!");
    }
 
 
 
 
    @SubscribeMapping("/age")
    @SendTo("/topic/age")
    public Greeting greetingAge(HelloMessage message) throws Exception {
        System.out.println("HelloMessage age "+ message.getName());
        return new Greeting(message.getName() + "? Are you really so old?");
    }
 
 
    @SendTo("/topic/greetings")
    public Greeting greetingAuto(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        message.setName(message.getName()+" Auto!");
        System.out.println("Auto HelloMessage message "+ message.getName());
        return new Greeting("Auto Hello, " + message.getName() + "!");
    }
    // greetingAuto nie wysyła do /topic/greetings a jedynie zmienia message
    
    public void broadcastMess(HelloMessage message) throws Exception {
 
        System.out.println("broadcastMess "+ message.getName());
     messaging.convertAndSend("/topic/greetings", new Greeting("broadcastMess " + message.getName() + "!"));
     // javascript musi odbierać tylko Greeting
    }



app.js has two stompClient.subscribe methods and three send methods:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var stompClient = null;
 
function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
        $("#ageConversation").show();
    }
    else {
        $("#conversation").hide();
        $("#ageConversation").hide();
    }
    $("#greetings").html("");
//    $("#age").html("");
}
 
function connect() {
    var socket = new SockJS('/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
        stompClient.subscribe('/topic/age', function (greeting) {
            showAge(JSON.parse(greeting.body).content);
        });
    });
}
 
function disconnect() {
    if (stompClient != null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}
 
function sendName() {
    stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
 
function sendSurName() {
    stompClient.send("/app/helloagain", {}, JSON.stringify({'name': $("#surname").val()}));
}
 
function sendAge() {
    stompClient.send("/app/age", {}, JSON.stringify({'name': $("#age").val()}));
}
 
function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}
 
function showAge(message) {
    $("#ageArea").append("<tr><td>" + message + "</td></tr>");
}
 
$(function () {
    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() { connect(); });
    $( "#disconnect" ).click(function() { disconnect(); });
    $( "#send" ).click(function() { sendName(); });
    $( "#sendsurname" ).click(function() { sendSurName(); });
    $( "#sendage" ).click(function() { sendAge(); });
});



And index.html:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html>
<head>
    <title>Hello WebSocket</title>
    <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/main.css" rel="stylesheet">
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script src="/app.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being
    enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div id="main-content" class="container">
    <div class="row">
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="connect">WebSocket connection:</label>
                    <button id="connect" class="btn btn-default" type="submit">Connect</button>
                    <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect
                    </button>
                </div>
            </form>
        </div>
        <div class="col-md-6">
            <form class="form-inline">
            
                <div class="form-group">
                    <label for="name">What is your name?</label>
                    <input type="text" id="name" class="form-control" placeholder="Your name here...">
                </div>
                <button id="send" class="btn btn-default" type="submit">Send</button>
                
                <div class="form-group">
                    <label for="surname">What is your surname?</label>
                    <input type="text" id="surname" class="form-control" placeholder="Your surname here...">
                </div>
                <button id="sendsurname" class="btn btn-default" type="submit">Send</button>
                
                <div class="form-group">
                    <label for="age">What is your age?</label>
                    <input type="text" id="age" class="form-control" placeholder="Your surname here...">
                </div>
                <button id="sendage" class="btn btn-default" type="submit">Send</button>
                
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <table id="conversation" class="table table-striped">
                <thead>
                <tr>
                    <th>Greetings</th>
                </tr>
                </thead>
                <tbody id="greetings">
                </tbody>
            </table>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <table id="ageConversation" class="table table-striped">
                <thead>
                <tr>
                    <th>Age</th>
                </tr>
                </thead>
                <tbody id="ageArea">
                </tbody>
            </table>
        </div>
    </div>
    </form>
</div>
</body>
</html>




Brak komentarzy:

Prześlij komentarz