用golnd写一个websocket消费者程序代码
时间: 2024-06-03 12:10:49 浏览: 148
websocket编程代码
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// 校验 Origin header,确保连接不是恶意的
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func reader(conn *websocket.Conn) {
for {
// 读取 websocket 的消息
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
fmt.Println(string(p))
if err := conn.WriteMessage(messageType, p); err != nil {
log.Println(err)
return
}
}
}
func serveWs(w http.ResponseWriter, r *http.Request) {
// 将 HTTP 连接升级为 websocket 连接
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
reader(conn)
}
func setupRoutes() {
http.HandleFunc("/ws", serveWs)
}
func main() {
fmt.Println("WebSocket Chat Application")
setupRoutes()
http.ListenAndServe(":8080", nil)
}
阅读全文