目的:服务端主动推送信息到客户端
package main
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/websocket"
"github.com/kataras/neffos"
"log"
"time"
)
type MyWebSocket struct {
ws *neffos.Server
conns map[*neffos.Conn]string//map的value存储uid,用于区分用户
}
func NewSocket() *MyWebSocket {
ws := MyWebSocket{
conns: make(map[*neffos.Conn]string),
}
return &ws
}
// SetUID 设置用户信息
func (this *MyWebSocket) SetUID(con *neffos.Conn, uid string) {
myWebSocket.conns[con] = uid
}
// DelConn 移除连接
func (this *MyWebSocket) DelConn(c *neffos.Conn) {
delete(this.conns, c)
}
var myWebSocket *MyWebSocket
func main() {
app := iris.New()
myWebSocket = NewSocket()
Handle(app, "/msg")
go func() { //推送消息
defer func() {
if err := recover(); err != nil {
log.Printf("recover:%v", err)
}
}()
time.Sleep(1 * time.Minute)
Send("308857")
}()
app.Run(iris.Addr(":8080"))
}
func Handle(app *iris.Application, path string) {
myWebSocket.ws = websocket.New(websocket.DefaultGorillaUpgrader, websocket.Events{
websocket.OnNativeMessage: func(nsConn *websocket.NSConn, msg websocket.Message) error {
log.Printf("Server got: %s from [%s]", msg.Body, nsConn.Conn.ID())
return nil
},
})
//连接时设置用户信息
myWebSocket.ws.OnConnect = func(c *websocket.Conn) error {
log.Printf("[%s] Connected to server!", c.ID())
ctx := websocket.GetContext(c)
uid := ctx.URLParam("uid")
myWebSocket.SetUID(c, uid)
return nil
}
myWebSocket.ws.OnDisconnect = func(c *websocket.Conn) {
myWebSocket.DelConn(c)
log.Printf("[%s] Disconnected from server", c.ID())
}
myWebSocket.ws.OnUpgradeError = func(err error) {
log.Printf("Upgrade Error: %v", err)
}
app.Get(path, websocket.Handler(myWebSocket.ws))
}
// Send 给指定用户发送消息
func Send(uid string) {
cons := myWebSocket.conns
for con, u := range cons {
if u == uid {
isSuc := con.Write(websocket.Message{
Body: []byte(fmt.Sprintf("主动推送")),
})
if isSuc {
log.Print(uid, "成功")
}
}
}
}
/*
群发本质上就是给多条连接推送信息
*/
测试工具:postman
测试结果: