要實現一個golang的websocket聊天室,可以遵循以下步驟:
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
ChatRoom
結構體,包含一個clients
映射表,用于保存所有連接的客戶端:type ChatRoom struct {
clients map[*websocket.Conn]bool
}
handleWebSocket
函數,用于處理websocket連接請求:func (c *ChatRoom) handleWebSocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
c.clients[conn] = true // 將新連接的客戶端加入到映射表中
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println(err)
delete(c.clients, conn) // 若發生錯誤,刪除該連接
return
}
for client := range c.clients {
err := client.WriteMessage(messageType, p)
if err != nil {
log.Println(err)
client.Close()
delete(c.clients, client) // 若發生錯誤,刪除該連接
}
}
}
}
main
函數中初始化ChatRoom
并設置路由:func main() {
chatRoom := &ChatRoom{
clients: make(map[*websocket.Conn]bool),
}
http.HandleFunc("/ws", chatRoom.handleWebSocket)
log.Fatal(http.ListenAndServe(":8080", nil))
}
這樣,你就實現了一個簡單的golang websocket聊天室。當有新的客戶端連接進來時,將其加入到clients
映射表中,并循環讀取每個客戶端發送的消息,然后將消息廣播給所有其他連接的客戶端。當發生任何錯誤時,需要關閉連接并從clients
映射表中刪除該連接。