Skip to content

Instantly share code, notes, and snippets.

@jechol
Created June 10, 2025 08:23
Show Gist options
  • Save jechol/1a6b2a49c1b1b67855c12ab121def0d0 to your computer and use it in GitHub Desktop.
Save jechol/1a6b2a49c1b1b67855c12ab121def0d0 to your computer and use it in GitHub Desktop.
Phoenix Channel 을 이용한 채팅
defmodule HelloWeb.SampleRoomChannel do
use HelloWeb, :channel
@impl true
def join("sample_room:lobby", _payload, socket) do
{:ok, socket}
end
@impl true
def handle_in("new_msg", %{"msg" => msg}, socket) do
# 수신한 메시지를 "sample_room:lobby" 에 조인한 모든 클라이언트에게 발신
broadcast!(socket, "new_msg", %{msg: msg})
{:noreply, socket}
end
end
// 웹소켓 연결
import { Socket } from "phoenix"
let socket = new Socket("/ws/sample_chat", { params: { token: window.userToken } });
socket.connect();
// "sample_room:lobby" 에 조인
let channel = socket.channel("sample_room:lobby", {});
channel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) });
// 메시지 발신 셋업
const form = document.getElementById('chat-form');
form.addEventListener('submit', function(e) {
const input = document.getElementById('chat-input');
channel.push("new_msg", {msg: input.value});
});
// 메시지 수신 셋업
channel.on("new_msg", function({msg}) {
const messages = document.getElementById('messages');
const div = document.createElement('div');
div.textContent = msg;
messages.appendChild(div);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment