gin实现聊天代码
时间: 2023-12-11 18:03:50 浏览: 92
聊天程序代码
以下是一个使用 Gin 和 WebSocket 实现简单聊天功能的示例代码:
```go
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type Message struct {
Username string `json:"username"`
Content string `json:"content"`
}
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)
func main() {
r := gin.Default()
// 打开 WebSocket 连接
r.GET("/ws", func(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
fmt.Println("Failed to open WebSocket connection:", err)
return
}
clients[conn] = true
// 循环接收客户端发送的消息
for {
var msg Message
err := conn.ReadJSON(&msg)
if err != nil {
fmt.Println("Failed to read message from client:", err)
delete(clients, conn)
conn.Close()
break
}
// 处理客户端发送的消息
fmt.Printf("Received message from %s: %s\n", msg.Username, msg.Content)
// 广播消息给所有客户端
broadcast <- msg
}
})
// 广播消息给所有客户端
go func() {
for {
msg := <-broadcast
for conn := range clients {
err := conn.WriteJSON(msg)
if err != nil {
fmt.Println("Failed to send message to client:", err)
delete(clients, conn)
conn.Close()
}
}
}
}()
// 启动服务
err := http.ListenAndServe(":8080", r)
if err != nil {
fmt.Println("Failed to start server:", err)
}
}
```
这个示例中,我们定义了一个 `Message` 结构体,包含用户名和内容两个字段。客户端通过 WebSocket 连接发送消息时,服务端会将消息解析为 `Message` 结构体,并将其广播给所有客户端。同时,服务端也会监听客户端连接的断开,并在客户端断开连接时从 `clients` 中删除该客户端的连接信息。
阅读全文