Go: IM系统接入ws进行消息发送以及群聊功能
package main
import (
"fmt"
"github.com/gorilla/websocket"
"net/http"
)
var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)
func main() {
http.HandleFunc("/", handleConnections)
http.HandleFunc("/ws", handleWebSocket)
go handleMessages()
fmt.Println("Starting server on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
// 这里可以添加你的HTML文件路径,并提供用户界面
fmt.Fprintf(w, "Hello, you've connected!")
}
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
clients[conn] = true
fmt.Println("Connected clients:", len(clients))
defer func() {
delete(clients, conn)
fmt.Println("Connected clients:", len(clients))
conn.Close()
}()
for {
var msg Message
if err := conn.ReadJSON(&msg); err != nil {
fmt.Println(err)
return
}
broadcast <- msg
}
}
func handleMessages() {
for {
msg := <-broadcast
for client := range clients {
err := client.WriteJSON(msg)
if err != nil {
fmt.Println(err)
client.Close()
}
}
}
}
这个代码示例提供了一个简单的Go语言服务器,用于处理WebSocket连接和消息广播。它使用gorilla/websocket库来处理WebSocket请求,并且提供了群聊功能。代码中包含了错误处理和连接管理,是一个实际可用的WebSocket服务器示例。
评论已关闭