[Lettrip] 채팅 기능 간단 테스트

subbni·2023년 10월 13일

Lettrip

목록 보기
7/7

의존성 추가

implementation 'org.springframework.boot:spring-boot-starter-websocket'

WebSocketConfig

package com.lettrip.lettripbackend.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
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
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    /* 웹소켓 서버의 엔드포인트와 클라이언트 origin 등록 */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("ws/chat")
                .setAllowedOrigins("*"); //  (*: 모든 origin 허용)
        // TODO: 배포시 특정 origin만 등록하기
    }

    /* 어플리케이션 내부에서 사용할 path를 지정 */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/sub");
        // 클라이언트 사용자의 구독 경로 "/sub"
        // 해당 경로로 SimpleBroker 등록, SimpleBroker는 해당하는 경로를 SUBSCRIBE하는 Client에게 메세지 전달
        registry.setApplicationDestinationPrefixes("/pub");
        // 메세지 발송 경로 "/pub"
        // /pub가 prefix로 붙은 메세지는 @MessageMapping이 붙은 메서드로 바운드

    }
}

ChatDto

package com.lettrip.lettripbackend.controller.chat.dto;

import lombok.Data;

@Data
public class ChatDto {
    private Integer channelId;
    private Integer roomId;
    private Integer writerId;
    private String message;
}

테스트용으로 일단 단순히 구성했다.

ChatRoomDto

package com.lettrip.lettripbackend.controller.chat.dto;

public class ChatRoomDto {
    private Integer roomId;
    private String name;

}

WebSocketController

package com.lettrip.lettripbackend.controller.chat;

import com.lettrip.lettripbackend.controller.chat.dto.ChatDto;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;

/*
    /sub/channel/12345          - 구독(channelId:12345)
    /pub/hello                  - 메시지 발행
 */
@RestController
@RequiredArgsConstructor
public class WebSocketController {
    private final SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/hello")
    public void sendMessage(ChatDto chatDto, SimpMessageHeaderAccessor accessor) {
        simpMessagingTemplate.convertAndSend("/sub/channel/"+chatDto.getChannelId(), chatDto);
        // /sub/chat/{channelId} 채널을 구독 중인 클라이언트에게 메시지를 전송한다.
        // 메시지의 payload는 인자(chatDto)로 들어온다.
    }
}

테스트

테스트를 위해 Apic을 사용했다.

1. 구독하는 클라이언트 생성

2. 구독하는 또 다른 클라이언트 생성

3. 한 클라이언트에서 메세지 발신

그럼 이렇게 구독 중인 다른 클라이언트에 메세지가 오는 것을 확인할 수 있다.

profile
개발콩나물

0개의 댓글