Skip to main content

채팅 서버 도입을 위한 Golang RTC 소개

Go - Melody(Real time communication)

who: Alex

Untitled

목적

golang 에서 websocket 관련 대표적으로 사용되는 라이브러리인 melody 라이브러리를 통해 채팅룸 구현된 예제를 스터디 해 보려 함.

개념

프론트 상에서 javascript 에서 제공하는 WebSocket 객체를 사용하고 백엔드 상에서는 melody 를 활용해 websocket 을 컨트롤해 채팅이 구현된다.

개발

package main

import (
"fmt"
"net/http"

"github.com/gin-gonic/gin"
"gopkg.in/olahol/melody.v1"
)

func main() {
r := gin.Default()
m := melody.New()

r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
})
r.GET("/chatroom", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "chatroom.html")
})

r.GET("/ws", func(c *gin.Context) {
fmt.Println("ws request")
m.HandleRequest(c.Writer, c.Request)
})

m.HandleMessage(func(s *melody.Session, msg []byte) {
fmt.Println("ws broadcast")
m.Broadcast(msg)
})

r.Run(":5000")
}
  1. gin 라이브러리를 활용해 간단하게 백엔드 서버를 구현한다.

  2. /chatroom path 로 접속 시 chatroom.html 파일을 서비스 한다.

  3. 프론트에서 웹 소켓을 만들면서 /ws path를 요청해 melody 객체 m을 만들어 m.handleRequestgin.ResponseWriter, http.Request 를 넘겨 웹소켓을 연결함.

  4. 프론트에서 넘어온 msgm.handleMessage 를 이용해 받아 m.Broadcast 를 활용해 /ws 에 연결된 모든 사용자에게 msg 를 넘긴다.

<html>
<head>
<title>Melody Chat Room</title>
</head>

<style>
#chat {
text-align: left;
background: #f1f1f1;
width: 500px;
min-height: 300px;
padding: 20px;
}
</style>

<body>
<center>
<a href="/">come back</a>
<h3>You are in the Room</h3>
<pre id="chat"></pre>
<input placeholder="say something" id="text" type="text" />
</center>

<script>
var url = "ws://" + window.location.host + "/ws";
var ws = new WebSocket(url);
var name = "Guest" + Math.floor(Math.random() * 1000);

var chat = document.getElementById("chat");
var text = document.getElementById("text");

var now = function () {
var iso = new Date().toISOString();
return iso.split("T")[1].split(".")[0];
};

ws.onmessage = function (msg) {
console.log("ws on message");
var line = now() + " " + msg.data + "\n";
chat.innerText += line;
};

text.onkeydown = function (e) {
if (e.keyCode === 13 && text.value !== "") {
console.log("ws send");
ws.send("<" + name + "> " + text.value);
text.value = "";
}
};
</script>
</body>
</html>
  1. chatroom 페이지에 들어온 순간 url 을 불러와 웹소켓 객체 ws를 만든다.

  2. 채팅을 쓰고 엔터를 누르면 화면에 id=textinput 태그의 값을 불러와 웹소켓의 ws.send 를 활용해 msg 를 서버로 넘긴다.

  3. 서버에서 넘어온 msgws.onmessage 에서 받아 채팅창에 msg 를 추가해 채팅이 가능하게 함.

결론

javascript 의 websocket 객체와 melody 를 활용해 메시지를 주고받으며 간단하게 채팅방을 구현할 수 있음.