为什么没有一种连接和发送websocket的方法?

时间:2016-07-31 15:18:56

标签: javascript spring websocket spring-websocket java-websocket

我是新的websocket并参考下面的Spring Websocket教程,它在我的系统中运行良好。我也在使用stomp.js和sockjs-0.3.4.js。

https://spring.io/guides/gs/messaging-stomp-websocket/

如果html和javascript有两个不同的方法,如下所示,它可以工作。

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

function sendName() {
    var name = document.getElementById('name').value;
    stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}

如果我编写一个单独的javascript函数,如下所示,它不起作用并将错误视为未捕获错误:INVALID_STATE_ERR

function startAndSend() {
            connect();
            sendName();
        }

我想知道它为什么不起作用。这可能是一个愚蠢的问题,请在这方面帮助我。我在下面提供了完整的html文件。是否总是需要编写html按钮进行连接并将信息发送到websocket,如Spring Websocket示例中所示?是不是可以点击按钮,它将连接并发送信息到websocket?这对我来说似乎很奇怪,我需要你的帮助。

<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<script src="sockjs-0.3.4.js"></script>
<script src="stomp.js"></script>
<script type="text/javascript">
        var stompClient = null;

        function setConnected(connected) {
            document.getElementById('response').innerHTML = '';
        }

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

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

        function sendName() {
            var name = document.getElementById('name').value;
            stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
        }

        function showGreeting(message) {
            var response = document.getElementById('response');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            console.log(message);
            p.appendChild(document.createTextNode(message));
            response.appendChild(p);
        }


        //Does not work
        function startAndSend() {
            connect();
            sendName();
        }
    </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>
        Stomp Over Websocket using Spring
        <div>
            <button id="connect" onclick="connect();">Connect</button>
            <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
            <button id="check" onclick="startAndSend();">StartAndSend</button>
        </div>
        <div id="conversationDiv">
            <label>What is your name?</label><input type="text" id="name" />
            <button id="sendName" onclick="sendName();">Send</button>
            <p id="response"></p>
        </div>

    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

这是因为stompClient.connect()方法是异步的,并且在sendName()连接尚未建立之后立即致电connect()

您应该在sendName()回调中调用stompClient.connect(),以确保在sendName()调用时建立连接。

例如:

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

答案 1 :(得分:0)

不熟悉Stomp(所以只是猜测):实际的stompClient.connect调用将回调作为第二个参数。这表明这是异步运行的。您尝试使用连接然后失败,因为它是在实际建立连接之前执行的。尝试将调用放入connect函数的回调中时会发生什么。