본문 바로가기
개발/기능 구현, 프로젝트

websocket 설정( js, spring boot)

by 개발자종혁 2021. 3. 31.
728x90

front end (js)

1. npm install

npm i sockjs-client      
npm i stompjs

2. connect하는 js 파일

import SockJS from "sockjs-client";
import Stomp from "stompjs";

var stompClient = null;

export function connect() {

  const headers = {
    // connect, subscribe에 쓰이는 headers
  };

  var socket = new SockJS(`<base URL - 웹소켓 서버 주소>/ws`);
  stompClient = Stomp.over(socket);

  stompClient.connect(
    headers,
    frame => {

      stompClient.subscribe(
        "<subscribe하는 topic>",
        () => {
          // subscribe 후 실행하는 곳
        },
        headers
      );
    },
    () => {
      // disconnect 시 실행 되는 곳
    }
  );
}

export function disConnect() {
  if (stompClient !== null) {
    const headers = {

      // disconnect에 쓰이는 headers
    };
    stompClient.disconnect(function () {
      // disconnect 후 실행하는 곳
    }, headers);
  }
}

web socket server (spring boot)

1. build.gradle

    plugins {
     id 'org.springframework.boot' version '2.3.1.RELEASE'
    }
    ...
    dependencies {
     // web
     implementation 'org.springframework.boot:spring-boot-starter-web'
     implementation 'org.springframework.boot:spring-boot-starter-websocket'

    }

2. web socket session config


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;


@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketSessionConfig extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> {


    @Override
    protected void configureStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setAllowedOrigins("*")
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
       // 30000ms 마다 연결확인하고
        long[] heartbeart = {30000l, 30000l};
        // topic broker 등록
        registry.enableSimpleBroker("/topic").setTaskScheduler(heartBeatScheduler()).setHeartbeatValue(heartbeart);
        registry.setApplicationDestinationPrefixes("/prefix-for-app");

    }


    // heart beat: 연결 확인 지속적으로 하는 것
    @Bean
    public TaskScheduler heartBeatScheduler() {
        return new ThreadPoolTaskScheduler();
    }
}
728x90

댓글