GolangWebSocket聊天室实战教程
时间:2025-12-16 11:14:52 393浏览 收藏
哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《Golang实现简单聊天室_Golang WebSocket实战》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
使用gorilla/websocket库搭建WebSocket服务器,通过Upgrade将HTTP连接升级为WebSocket连接,实现客户端与服务端的双向通信。2. 定义全局clients map和broadcast通道,利用协程监听广播消息并推送给所有活跃连接,实现消息的实时群发。

用Golang实现一个简单聊天室,核心是利用WebSocket建立客户端与服务端的长连接,实现消息的实时双向通信。下面一步步带你完成一个基础但完整的聊天室demo。
1. 搭建WebSocket服务器
Go标准库没有内置WebSocket支持,需借助第三方库,推荐使用 gorilla/websocket,安装方式:
go get github.com/gorilla/websocket创建主服务文件 main.go,初始化路由和WebSocket处理函数:
package main
<p>import (
"log"
"net/http"
"github.com/gorilla/websocket"
)</p><p>var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // 允许跨域
},
}</p><p>func handleConnections(w http.ResponseWriter, r *http.Request) {
// 升级HTTP连接为WebSocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
return
}
defer ws.Close()</p><pre class="brush:php;toolbar:false"><code>// 新用户加入后,持续监听消息
for {
var msg string
err := ws.ReadJSON(&msg)
if err != nil {
log.Printf("读取消息失败: %v", err)
break
}
// 广播消息给所有客户端(后续实现)
broadcastMessage(msg, ws)
}</code>}
func main() { http.HandleFunc("/ws", handleConnections) http.Handle("/", http.FileServer(http.Dir("./public"))) log.Println("服务器运行在 :8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
2. 管理客户端连接
需要一个全局结构来保存所有活跃的WebSocket连接,以便广播消息。
定义 clients map 和广播通道:
var (
clients = make(map[*websocket.Conn]bool) // 所有连接
broadcast = make(chan string) // 广播消息通道
)
启动一个后台协程,监听广播通道并推送消息给每个客户端:
func handleMessages() {
for {
msg := <p>在 main 函数中启动该协程:</p><font face="Courier New">
go handleMessages()
</font><p>修改 handleConnections,在连接建立时注册客户端:</p><p></p><pre class="brush:php;toolbar:false;">clients[ws] = true
3. 实现消息广播
当某个客户端发来消息,将其推入 broadcast 通道:
func broadcastMessage(msg string, sender *websocket.Conn) {
broadcast <p>这样 handleMessages 协程会自动将消息发送给所有在线用户。</p><h3>4. 编写前端页面</h3><p>在项目目录下创建 public/index.html:</p><p></p><pre class="brush:php;toolbar:false;"><!DOCTYPE html>
<html>
<head>
<title>Go 聊天室</title>
</head>
<body>
<h2>聊天室</h2>
<div id="chat"></div>
<input type="text" id="msg" placeholder="输入消息" />
<button onclick="send()">发送</button>
<p><script>
const ws = new WebSocket("ws://localhost:8080/ws");
const chatBox = document.getElementById("chat");
const input = document.getElementById("msg");</p><pre class="brush:php;toolbar:false"><code>ws.onmessage = function(event) {
const div = document.createElement("div");
div.textContent = event.data;
chatBox.appendChild(div);
};
function send() {
if (input.value) {
ws.send(input.value);
input.value = "";
}
}</code>