websocket.js 2.59 KB
var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    var socket = new SockJS('/wms/endpoint');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/message', function (greeting) {
            // showGreeting(JSON.parse(greeting.body).content);
            showGreeting(greeting.body);
        });
        stompClient.subscribe('/user/topic/message', function (greeting) {
            // showGreeting(JSON.parse(greeting.body).content);
            showGreeting(greeting.body);
        });
    });
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    // stompClient.send("/app/websocket/message/string", {}, JSON.stringify({'msg': $("#name").val()}));
    stompClient.send("/app/websocket/message/string", {},  $("#name").val());
}

function sendJson() {
    // stompClient.send("/app/websocket/message/string", {}, JSON.stringify({'msg': $("#name").val()}));
    stompClient.send("/app/websocket/message/json", {},  $("#json").val());
}

function sendMsg() {
    $.ajax({
        url: "/wms/websocket/message/string?msg=" + $("#msg").val(),
        // data: formdata,
        type: "get",
        processData: false,
        contentType: false,
        success: function(result) {
            $.operate.saveSuccess(result);
        }
    })
}

function sendJson2() {
    $.ajax({
        url: "/wms/websocket/message/json",
        data: $("#json2").val(),
        type: "post",
        dataType : 'json',
        processData: false,
        contentType: 'application/json',
        success: function(result) {
            $.operate.saveSuccess(result);
        }
    })
}

function showGreeting(message) {
    $("#greetings").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(); });
    $( "#send2" ).click(function() { sendJson(); });
    $( "#send3" ).click(function() { sendMsg(); });
    $( "#send4" ).click(function() { sendJson2(); });
});