- vừa được xem lúc

Websocket - Chat in real-time with Golang

0 0 8

Người đăng: Nguyen Van Tuan

Theo Viblo Asia

image.png

I. How to the system work?

image.png

I will start with 2 channels: Alice and Bob. When Alice enters the message chat, it will send data to the web socket server with channel Alice. We will receive the data and write the message data to Bob's channel -> Bob will read the message. The opposite will be the same.

II. Implement

1. Back-end

var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024,
} var mapWsConn = make(map[string]*websocket.Conn) func main() { http.HandleFunc("/chat", LoadPageChat) http.HandleFunc("/ws", InitWebsocket) log.Fatal(http.ListenAndServe(":3000", nil))
}

The main goroutine will init 2 API: load page chat and init web socket server. The server will run in port 3000

func LoadPageChat(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") path, err := os.Getwd() if err != nil { fmt.Fprintf(w, "%s", "error") return } content, err := os.ReadFile(path + "/chat-using-websocket/chat.html") if err != nil { fmt.Fprintf(w, "%s", "error") return } fmt.Fprintf(w, "%s", content)
}

The function LoadPageChat will read the file chat.html and handle the user interface. The API will return HTML for front-end to display for the user.

func InitWebsocket(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") channel := r.URL.Query().Get("channel") if r.Header.Get("Origin") != "http://"+r.Host { fmt.Fprintf(w, "%s", "error") return } if _, ok := mapWsConn[channel]; !ok { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { fmt.Fprintf(w, "%s", "error") return } mapWsConn[channel] = conn } for { var msg map[string]string err := mapWsConn[channel].ReadJSON(&msg) if err != nil { fmt.Println("Error reading JSON:", err) break } fmt.Printf("Received: %s\n", msg) otherConn := getConn(channel) if otherConn == nil { continue } err = otherConn.WriteJSON(msg) if err != nil { fmt.Println("Error writing JSON:", err) break } }
} func getConn(channel string) *websocket.Conn { for key, conn := range mapWsConn { if key != channel { return conn } } return nil
}

The function will init web socket's connection. We will consume the channel to get the message and send it to another channel.

Example: Alice sends the message "Hi" to channel Alice -> the channel Alice will receive "Hi" -> write the message "Hi" to channel Bob

2. Front-end

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"> <title>Chat application</title>
</head>
<body>
<div class="container"> <div class="chat"> <div class="santaSays"> <div class="text-box-santa"> <div class="text"> <p>Hi there, my child!</p> <p>What can I help you with?</p> </div> </div> </div> <div class="userSays"> <div class="text"> <p>Hello, Santa!</p> <p>I'd like to know when you'll bring my gift?</p> </div> </div> </div> <hr> <div class="message-box"> <div class="message-input"> <input id="inputText" type="text" placeholder="What can I help you with?"> </div> <div class="send-btn"> <i class="fa-solid fa-paper-plane plane"></i> </div> </div>
</div>
</body>
</html>

image.png

This is the chat application interface.

<script> const chat = document.querySelector(".chat"); const inputText = document.getElementById("inputText"); let ws; if (window.WebSocket === undefined) { console.log("Your browser does not support WebSockets") } else { ws = initWS(); } function initWS() { let socket = new WebSocket("ws://" + window.location.host + "/ws" + window.location.search) socket.onopen = function() { console.log("Socket is open") }; // receive data from server socket.onmessage = function (e) { let pS = document.createElement("p"); pS.innerHTML = JSON.parse(e.data).message; pS.classList.add("santaMessage"); chat.appendChild(pS); chat.scrollTop = chat.scrollHeight; } // close socket socket.onclose = function () { console.log("Socket closed") } return socket; } inputText.addEventListener("keyup", (e) => { if (e.key === "Enter") { let pU = document.createElement("p"); pU.innerHTML = inputText.value; pU.classList.add("userMessage"); chat.appendChild(pU); chat.scrollTop = chat.scrollHeight; ws.send(JSON.stringify({message: inputText.value})); inputText.value = ""; } })
</script>

The source JavaScript loads the page, init web socket, sends the message to the web socket server and displays it to the interface.

III. Result

image.png image.png

Video demo

IV. Reference

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 522

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 432

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 153

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 141

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 110

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 244