44 lines
1.0 KiB
Go
44 lines
1.0 KiB
Go
package ws
|
|
|
|
import (
|
|
"MossChat/logger"
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"log"
|
|
"nhooyr.io/websocket"
|
|
)
|
|
|
|
type ChatServer struct {
|
|
ServerName string
|
|
RelativePath string
|
|
ctx *gin.Context
|
|
}
|
|
|
|
func (sv *ChatServer) Bind(engine *gin.Engine) *ChatServer {
|
|
engine.GET(sv.RelativePath, func(context *gin.Context) {
|
|
options := websocket.AcceptOptions{
|
|
InsecureSkipVerify: true,
|
|
}
|
|
accept, err := websocket.Accept(context.Writer, context.Request, &options)
|
|
if err != nil {
|
|
logger.Log.Println("无法接受请求!:", err)
|
|
return
|
|
}
|
|
go sv.HandleConnections(accept)
|
|
sv.ctx = context
|
|
})
|
|
logger.Log.Println("已创建Websocket聊天服务器:", sv.ServerName, "在", sv.RelativePath)
|
|
return sv
|
|
}
|
|
func (sv *ChatServer) HandleConnections(conn *websocket.Conn) {
|
|
defer conn.CloseNow()
|
|
for {
|
|
_, dat, err := conn.Read(sv.ctx)
|
|
if websocket.CloseStatus(err) == websocket.StatusNormalClosure || websocket.CloseStatus(err) == websocket.StatusNoStatusRcvd {
|
|
log.Println("Websocket连接已关闭!")
|
|
return
|
|
}
|
|
fmt.Println(string(dat))
|
|
}
|
|
}
|