Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 带vue.js的Spring stomp WebSocket_Javascript_Spring_Vuejs2_Stomp_Spring Websocket - Fatal编程技术网

Javascript 带vue.js的Spring stomp WebSocket

Javascript 带vue.js的Spring stomp WebSocket,javascript,spring,vuejs2,stomp,spring-websocket,Javascript,Spring,Vuejs2,Stomp,Spring Websocket,我正在尝试将SpringWebSockets(STOMP)与Vue一起使用,但不知道如何使用,或者它是否可行。我的WebSocket使用普通JS,但当我尝试使用Vue时,我会被卡住。以下是我的vue代码: var app = new Vue({ el: '#app', data: { stompClient: null, gold: 0 }, methods: { sendEvent: function () { this.stompClient.send

我正在尝试将SpringWebSockets(STOMP)与Vue一起使用,但不知道如何使用,或者它是否可行。我的WebSocket使用普通JS,但当我尝试使用Vue时,我会被卡住。以下是我的vue代码:

var app = new Vue({
el: '#app',
data: {
    stompClient: null,
    gold: 0
},
methods: {
    sendEvent: function () {
        this.stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
    }
},
created: function () {
    this.stompClient = Stomp.over(new SockJS('/gs-guide-websocket'));
    this.stompClient.connect()
    this.stompClient.subscribe('/topic/greetings', function (greeting) {
        console.log(JSON.parse(greeting.body).content);
    });
},
})

我的连接和发送功能正在工作,我可以在后端看到消息,但问题是订阅功能。它需要一个回调函数,但这永远不会启动。我还尝试在vue中创建一个方法并调用它

this.stompClient.subscribe('/topic/greetings', vueFunc())
但这也不起作用。我在家里找到了一些图书馆,但我不知道如何使用它,看起来真的很乱。我宁愿使用纯JS


有人有办法吗?谢谢

我也有同样的情况

这里似乎有一个可行的解决方案:


以下是Spring Boot Websocket(STOMP)和Vue CLI的工作示例。 (此处有更详细的说明)

  • 从下载Spring引导演示
  • WebSocketConfig

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket")
                .setAllowedOrigins("http://localhost:8081")
                .withSockJS();
    }
    
  • 运行项目
  • 现在启动Vue CLI项目并执行以下操作:

  • 安装SockJS
    npm安装SockJS客户端
  • 安装STOMP
    npm安装WebTomp客户端
  • 我使用引导类,所以您需要
    npm安装bootstrap@3
    仅用于布局
  • 添加.vue组件:

    <template>
        <div>
            <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" :disabled="connected == true" @click.prevent="connect">Connect</button>
                                <button id="disconnect" class="btn btn-default" type="submit" :disabled="connected == false" @click.prevent="disconnect">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" v-model="send_message" placeholder="Your name here...">
                            </div>
                            <button id="send" class="btn btn-default" type="submit" @click.prevent="send">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>
                                <tr v-for="item in received_messages" :key="item">
                                    <td>{{ item }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </template>
    
    <script>
    import SockJS from "sockjs-client";
    import Stomp from "webstomp-client";
    
    export default {
      name: "websocketdemo",
      data() {
        return {
          received_messages: [],
          send_message: null,
          connected: false
        };
      },
      methods: {
        send() {
          console.log("Send message:" + this.send_message);
          if (this.stompClient && this.stompClient.connected) {
            const msg = { name: this.send_message };
            this.stompClient.send("/app/hello", JSON.stringify(msg), {});
          }
        },
        connect() {
          this.socket = new SockJS("http://localhost:8080/gs-guide-websocket");
          this.stompClient = Stomp.over(this.socket);
          this.stompClient.connect(
            {},
            frame => {
              this.connected = true;
              console.log(frame);
              this.stompClient.subscribe("/topic/greetings", tick => {
                console.log(tick);
                this.received_messages.push(JSON.parse(tick.body).content);
              });
            },
            error => {
              console.log(error);
              this.connected = false;
            }
          );
        },
        disconnect() {
          if (this.stompClient) {
            this.stompClient.disconnect();
          }
          this.connected = false;
        },
        tickleConnection() {
          this.connected ? this.disconnect() : this.connect();
        }
      },
      mounted() {
        // this.connect();
      }
    };
    </script>
    
    <style scoped>
    
    </style>
    
    
    WebSocket连接:
    连接
    断开
    你的名字叫什么?
    发送
    问候语
    {{item}}
    从“SockJS客户端”导入SockJS;
    从“WebTomp客户端”导入Stomp;
    导出默认值{
    名称:“websocketdemo”,
    数据(){
    返回{
    收到的消息:[],
    发送消息:空,
    连接:false
    };
    },
    方法:{
    发送(){
    console.log(“发送消息:+this.Send_消息”);
    if(this.stompClient&&this.stompClient.connected){
    const msg={name:this.send_message};
    this.stompClient.send(“/app/hello”,JSON.stringify(msg),{});
    }
    },
    连接(){
    this.socket=新的SockJS(“http://localhost:8080/gs-导向网袋);
    this.stompClient=Stomp.over(this.socket);
    this.stompClient.connect(
    {},
    帧=>{
    this.connected=true;
    控制台日志(框架);
    this.stompClient.subscribe(“/topic/greetings”,勾选=>{
    控制台日志(勾选);
    this.received_messages.push(JSON.parse(tick.body).content);
    });
    },
    错误=>{
    console.log(错误);
    this.connected=false;
    }
    );
    },
    断开连接(){
    if(此.stompClient){
    this.stompClient.disconnect();
    }
    this.connected=false;
    },
    挠痒连接(){
    this.connected?this.disconnect():this.connect();
    }
    },
    安装的(){
    //这个.connect();
    }
    };
    

    运行项目并进行测试,默认情况下它应该在8081端口启动。

    你是我的英雄。令人难以置信的是,标准教程中没有提到
    .setAllowedOriginates(“*”)
    。谢谢任何人都遵循这个答案,WebTomp客户端的send()参数的顺序与stompjs不同,尽管这两个参数在教程中可以互换使用,WebTomp客户端的send(dest,msg,headers)和stompjs的send(dest,headers,msg)以及类似的参数