Skip to content

Broadcast function usage #93

Answered by lxzan
aworobel asked this question in Q&A
Discussion options

You must be logged in to vote
package main

import (
	"github.com/lxzan/gws"
)

func GetValueFromSession[T any](s gws.SessionStorage, k string) (value T, ok bool) {
	if v, exist := s.Load(k); exist {
		value, ok = v.(T)
	}
	return
}

type Handler struct {
	gws.BuiltinEventHandler
	conns *gws.ConcurrentMap[int64, *gws.Conn]
}

func (c *Handler) OnOpen(socket *gws.Conn) {
	userId, _ := GetValueFromSession[int64](socket.Session(), "userId")
	c.conns.Store(userId, socket)
}

func (c *Handler) OnClose(socket *gws.Conn, err error) {
	userId, _ := GetValueFromSession[int64](socket.Session(), "userId")
	c.conns.Delete(userId)
}

func (c *Handler) Broadcast(p []byte) {
	var b = gws.NewBroadcaster(gws.OpcodeText, p)
	defer b.Close

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by lxzan
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants