为什么没有一种连接和发送websocket的方法? [英] Why not one method to connect and send in websocket?

查看:167
本文介绍了为什么没有一种连接和发送websocket的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new websocket and refering to the below Spring Websocket tutorial and it is working fine in my system. I am also using stomp.js and sockjs-0.3.4.js.

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

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

If the html and javascript has two distinct methods like below, it works.

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

If I write a single javascript function as given below, it does not work and get the error as Uncaught Error: INVALID_STATE_ERR.

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

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

I want to know why it is not working. It may be dumb question, please help me in this regard. I provide below the complete html file. Is it always necessary to write html button for connect and send information to websocket as given in the Spring Websocket example ? Is it not possible to onClick of a button, it will connect and send information to websocket ? It seems to be a peculiar for me, I need your help.

<!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>


推荐答案

这是因为 stompClient。 connect()方法是异步的,当你在 connect() sendName()时>连接尚未建立。

That is because stompClient.connect() method is asynchronous and when you call sendName() right after connect() connection is not established yet.

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

You are supposed to call sendName() in stompClient.connect() callback to be sure that connection is established by the time sendName() invokes.

例如:

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

这篇关于为什么没有一种连接和发送websocket的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆