Rails 6 Action Cable

ayokinya·2020년 11월 1일
1

Rails 6로 채팅 프로그램을 만들기 시작했다.
여러 튜토리얼을 보고 간단하게 개념을 정리하고자 글을 쓴다.

Websocket

Websocket은 단일 TCP 연결로 서버와 클라이언트가 서로 데이터를 주고 받을 수 있게 한다. 기존 http 통신은 Client가 요청을 보내는 경우에만 Server가 응답하는 단방향 방식이고, Client가 Server로부터 응답을 받은 후에는 연결이 바로 종료된다. 그러나 Websocket 통신은 Server가 Client에게 요청을 보낼 수도 있고, Server와 Client 연결이 유지되기 때문에 실시간으로 소통이 가능하다.

Action Cable

Rails 6는 Action Cable에서 Websocket으로 실시간 통신을 지원한다. 그래서 채팅 프로그램을 구현하기 위해 Action Cable을 사용했다.
Websocket 연결 하나당 connection 하나가 생성된다. Websocket Client를 consumer라고 한다.consummer가 channel 하나를 구독하는 것을 subscription이라고 한다.
간단하게 예를 들어 rails g channel room으로 room_channel을 하나 생성한다고 하자. 그러면 app/channels/room_channel.rb에서

 def subscribed
 	stream_from "room_channel"
 end

로 room_channel을 구독하게 설정할 수 있다. unsubscribed일 때도 처리도 할 수 있다. 여기에서는 서버 쪽 behavior를 설정한다.

그 다음에는 messages controller나 job에서 create 함수에 message 내용을 room_channel로 방송할 수 있게 설정한다.

def create
	# ... 
	if message.save
    		ActionCable.server.broadcast( 'messages', body: message.body, author: message.author )
    	#...
end

broadcast 메소드를 사용하면 serialized JSON으로 Client 쪽에서 정보를 받게 된다.

app/javascript/channels/room_channel.js에서는 서버 연결과 데이터 받기 등 Websocket client 쪽 처리를 할 수 있다.

import consumer from "./consumer"

consumer.subscriptions.create("RoomChannel", {
 connected() {
   // Called when the subscription is ready for use on the server
   console.log("Connected to the room!")
 },

 disconnected() {
   // Called when the subscription has been terminated by the server
 },

 received(data) {
   // Called when there's incoming data on the websocket for this channel
   $('#msg').append('<div class="message"> ' + data.content + '</div>')
   console.log("Recieving:")
   console.log(data.content)
 }
});

let submit_messages;

$(document).on('turbolinks:load', function () {
 submit_messages()
})

submit_messages = function () {
 $('#message_content').on('keydown', function (event) {
   if (event.keyCode == 13) {
     $('input').click()
     event.target.value = ''
     event.preventDefault()
   }
 })
}

Action Cable을 간단하게 살펴봤다.

Chat in Rails 6를 검색하면 여러 튜토리얼이 나온다. 튜토리얼을 여러 번 하니까 이제서야 감이 온다. 하지만 감이 온 것과 구현하고 수정하는 것은 하늘과 땅 차이다. 이걸 바탕으로 많은 걸 해야 하는데 노력을 해도 제자리인 것 같아 답답하다. 채팅 기능을 원하는 대로 구현해 튜토리얼을 작성하고 싶다.

참고 자료
https://guides.rubyonrails.org/action_cable_overview.html
https://medium.com/@jelaniwoods/get-started-with-action-cable-in-rails-6-4c605f93c9b8

profile
42 서울 교육생

0개의 댓글