iris+websocket

目的:服务端主动推送信息到客户端

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

测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值