Ejemplo n.º 1
0
func broadCast(so socketio.Socket) {
	ticker := time.NewTicker(5 * time.Second)
	//quit := make(chan struct{})
	go func() {
		for {
			select {
			case <-ticker.C:
				var tasks = repos.GetRandomMockWorkItems()
				log.Println(len(tasks))
				m, _ := json.Marshal(tasks)
				so.Emit("work items", string(m))
				// do stuff
				//     case <- quit:
				//         ticker.Stop()
				//         return
			}
		}
	}()
}
Ejemplo n.º 2
0
func startServer(port int, cors_urls string) {
	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	server.On("connection", func(so socketio.Socket) {
		//log.Println(so.Request())
		log.Println("on connection")
		//so.Join("chat")
		m, _ := json.Marshal(repos.GetRandomMockWorkItems())
		so.Emit("work items", string(m))
		broadCast(so)
		// so.On("chat message", func(msg string) {
		// 	log.Println("emit:", so.Emit("chat message", msg))
		// 	so.BroadcastTo("chat", "chat message", msg)
		// })
		so.On("disconnection", func() {
			log.Println("on disconnect")
		})
	})
	server.On("error", func(so socketio.Socket, err error) {
		log.Println("error:", err)
	})

	// server.BroadcastTo("work items", )

	//add headers needed for CORS
	http.HandleFunc("/socket.io/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("Access-Control-Allow-Origin", cors_urls)
		w.Header().Add("Access-Control-Allow-Credentials", "true")
		server.ServeHTTP(w, r)
	})
	http.Handle("/", http.FileServer(http.Dir("./pub")))
	log.Println("Serving at localhost:5001...")
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}