programing

vue.js를 사용한 스프링 스톰프 웹소켓

nicescript 2022. 8. 23. 23:17
반응형

vue.js를 사용한 스프링 스톰프 웹소켓

Vue에서 Spring WebSockets(STOMP)를 사용하려고 하는데, 사용방법이나 사용가능성이 있는지조차 알 수 없습니다.내 웹소켓은 플레인 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())

하지만 그것도 효과가 없습니다.https://github.com/FlySkyBear/vue-stomp에서 몇 개의 도서관을 찾았는데 어떻게 사용하는지 알 수 없고 너무 지저분해 보여요.그럼 차라리 플레인 JS를 쓰죠.

해결책을 가진 사람?고마워요.

다음으로 Spring Boot Websocket(STOMP)과 Vue CLI의 작업 예를 나타냅니다(자세한 내용은 이쪽 http://kojotdev.com/2019/07/using-spring-websocket-stomp-application-with-vue-js/)).

  1. https://spring.io/guides/gs/messaging-stomp-websocket/ 에서 스프링 부트 데모를 다운로드 합니다.
  2. 허용된 오리진 추가 위치WebSocketConfig

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket")
                .setAllowedOrigins("http://localhost:8081")
                .withSockJS();
    }
    
  3. 프로젝트 실행

이제 Vue CLI 프로젝트를 시작하고 다음을 수행합니다.

  1. Sock 설치JSnpm install sockjs-client
  2. STOMP 설치npm install webstomp-client
  3. 난 부트스트랩 수업을 이용하니까npm install 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>

프로젝트를 실행하고 테스트를 수행합니다.기본적으로는 8081 포트에서 시작해야 합니다.

저도 같은 상황이에요.

여기에는 유효한 솔루션이 있는 것 같습니다.

https://github.com/ocinpp/springboot-sockjs-stomp-vue-sample

언급URL : https://stackoverflow.com/questions/46818674/spring-stomp-websockets-with-vue-js

반응형