Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package controllers
- import (
- "fmt"
- "github.com/kataras/iris"
- "github.com/kataras/iris/websocket"
- "sync"
- m "github.com/newapp/models"
- )
- var connWs = make(map[websocket.Connection]int)
- var mutex = new(sync.Mutex)
- var allowed = [4]string {"sta", "low", "fast", "store"}
- func SetupWebsocket(app *iris.Application) {
- ws := websocket.New(websocket.Config{
- ReadBufferSize: 4096,
- WriteBufferSize: 4096,
- EnableCompression: true,
- EvtMessagePrefix: []byte("d-wss:"),
- })
- ws.OnConnection(handleConnection)
- app.Get("/ws_point", ws.Handler())
- }
- func handleConnection(c websocket.Connection) {
- ctx := c.Context()
- // user identification
- fromMiddl := ctx.GetViewData()
- user := fromMiddl["u"].(m.User)
- mutex.Lock()
- connWs[c] = user.Id // Add user id from Middleware to Connections map
- mutex.Unlock()
- c.On("chat_add_msg", func(msg string) {
- })
- c.On("join", func(msg string) {
- for _, value := range allowed {
- c.Leave(value)
- if(msg == value) {
- c.Join(value)
- }
- }
- })
- c.OnDisconnect(func() {
- mutex.Lock()
- delete(connWs, c)
- mutex.Unlock()
- })
- }
- // Sending messages from other controllers by client ID or the entire room
- func Broadcast(id int, room, act, message string) {
- for с, uid := range connWs {
- if(id == 0) {
- с.To(room).Emit(act, message) // emit to all clients in room
- break
- } else if(uid == id) {
- с.Emit(act, message) // emit to one client by identifier
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement