今天的程式碼是使用Gorilla團隊提供的範例來修改及介紹,解釋一個使用WebSocket
與Gin
框架製作的聊天室。
先看一下這次小專案的結構
go-websocket
├── template
│ └── assets
│ │ └── style.css
│ │ └── script.js
│ └── home.html
├── client.go
├── hub.go
└── main.go
引入了bootstrap5
幫助排版,雖然幾乎沒用上
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chat Example</title>
<script src="./assets/script.js"></script>
<link rel="stylesheet" href="./assets/style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<div class="container">
<div id="log"></div>
<div style="align-items:center;">
<form id="form">
<input type="text" id="msg" size="64" autofocus />
<input type="submit" id="btn" value="Send" />
</form>
</div>
</div>
</body>
</html>
html {
overflow: hidden;
}
body {
overflow: hidden;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: gray;
}
div.container{
background-color: rgb(96, 222, 159);
padding: 2%;
margin-top: 30px;
}
#log {
border-radius: 50px;
height: 70vh;
background-color: aqua;
padding: 20px;
}
#form {
width: 100%;
overflow: hidden;
margin: 20px auto;
}
#msg{
width: 90%;
}
#btn{
width: 9%;
}
使用js
宣告websocket
物件,與後端溝通,並設置要呼叫的函式。
window.onload = function () {
var conn;
var msg = document.getElementById("msg");
var log = document.getElementById("log");
function appendLog(item) {
var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;
log.appendChild(item);
if (doScroll) {
log.scrollTop = log.scrollHeight - log.clientHeight;
}
}
document.getElementById("form").onsubmit = function () {
if (!conn) {
return false;
}
if (!msg.value) {
return false;
}
conn.send(msg.value);
msg.value = "";
return false;
};
if (window["WebSocket"]) {
conn = new WebSocket("ws://" + document.location.host + "/ws");
conn.onclose = function (evt) {
var item = document.createElement("div");
item.innerHTML = "<b>Connection closed.</b>";
appendLog(item);
};
conn.onmessage = function (evt) {
var messages = evt.data.split('\n');
for (var i = 0; i < messages.length; i++) {
var item = document.createElement("div");
item.innerText = messages[i];
appendLog(item);
}
};
} else {
var item = document.createElement("div");
item.innerHTML = "<b>Your browser does not support WebSockets.</b>";
appendLog(item);
}
};
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered clients.
clients map[*Client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
}
func newHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
}
}
func (h *Hub) run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}
管理使用者註冊、註銷,與訊息發送方法。
package main
import (
"bytes"
"log"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
const (
writeWait = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = (pongWait * 9) / 10
maxMessageSize = 512
)
var (
newline = []byte{'\n'}
space = []byte{' '}
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
// Client is a middleman between the websocket connection and the hub.
type Client struct {
hub *Hub
conn *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
}
// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *Client) readPump() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
c.hub.broadcast <- message
}
}
// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)
// Add queued chat messages to the current websocket message.
n := len(c.send)
for i := 0; i < n; i++ {
w.Write(newline)
w.Write(<-c.send)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
func serveWs(hub *Hub, ctx *gin.Context) {
ws, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
log.Println(err)
return
}
client := &Client{hub: hub, conn: ws, send: make(chan []byte, 256)}
client.hub.register <- client
go client.writePump()
go client.readPump()
}
serveWs
函式將http
連接升級成WebSocket
連線,建立與註冊客戶端,再交由hub.go
去進行管理。writePump
作為goroutine
啟動,會將客戶端發送的消息傳輸到WebSocket
中。readPump
同樣作為goroutine
啟動,將消息從Websocket
傳到hub
中,再由hub
反應給客戶端。// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"github.com/gin-gonic/gin"
)
func serveHome(c *gin.Context) {
ans := 1
c.HTML(200, "home.html", ans)
}
func main() {
hub := newHub()
go hub.run()
r := gin.Default()
r.LoadHTMLFiles("template/home.html")
r.Static("/assets", "./template/assets")
r.GET("/", serveHome)
r.GET("/ws",func(c *gin.Context) {
serveWs(hub, c)
})
r.Run(":8080")
}
將各種方法啟動與建立伺服器,接下來開啟兩個視窗都進入http://127.0.0.1:8080/
就能看見一個簡易的聊天室了。
變強都是從模仿開始的,今天的內容都是在講Gorilla團隊的使用範例,我只將範例從http
方式改成套用gin
框架來呈現,雖然沒有完全看懂這範例的程式碼,不過走一步算一步吧ˊˇˋ`