SHARE
TWEET

Untitled

a guest Aug 1st, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package controllers
  2.  
  3. import (
  4.     "fmt"
  5.  
  6.     "github.com/kataras/iris"
  7.     "github.com/kataras/iris/websocket"
  8.     "sync"
  9.     m "github.com/newapp/models"
  10. )
  11.  
  12.  
  13. var connWs = make(map[websocket.Connection]int)
  14. var mutex = new(sync.Mutex)
  15. var allowed = [4]string {"sta", "low", "fast", "store"}
  16.  
  17.  
  18.  
  19. func SetupWebsocket(app *iris.Application) {
  20.     ws := websocket.New(websocket.Config{
  21.         ReadBufferSize:    4096,
  22.         WriteBufferSize:   4096,
  23.         EnableCompression: true,
  24.         EvtMessagePrefix:  []byte("d-wss:"),
  25.     })
  26.     ws.OnConnection(handleConnection)
  27.    
  28.     app.Get("/ws_point", ws.Handler())
  29. }
  30.  
  31.  
  32.  
  33. func handleConnection(c websocket.Connection) {
  34. ctx := c.Context()
  35. //  user identification
  36. fromMiddl := ctx.GetViewData()
  37. user := fromMiddl["u"].(m.User)
  38.  
  39. mutex.Lock()
  40. connWs[c] = user.Id //  Add user id from Middleware to Connections map
  41. mutex.Unlock()
  42.  
  43.  
  44. c.On("chat_add_msg", func(msg string) {
  45.  
  46. })
  47.  
  48. c.On("join", func(msg string) {
  49.   for _, value := range allowed {
  50.      c.Leave(value)
  51.      
  52.      if(msg == value) {
  53.      c.Join(value)
  54.      }
  55.   }
  56. })
  57.  
  58.  
  59. c.OnDisconnect(func() {
  60. mutex.Lock()
  61. delete(connWs, c)
  62. mutex.Unlock()
  63. })
  64. }
  65.  
  66.  
  67. //  Sending messages from other controllers by client ID or the entire room
  68. func Broadcast(id int, room, act, message string) {
  69.   for с, uid := range connWs {
  70.     if(id == 0) {
  71.        с.To(room).Emit(act, message)  //  emit to all clients in room
  72.        break
  73.     } else if(uid == id) {
  74.        с.Emit(act, message)  //  emit to one client by identifier
  75.     }
  76.   }
  77. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top