Esempio n. 1
0
func echoHandler(session sockjs.Session) {
	log.Println("new sockjs session established")
	var closedSession = make(chan struct{})
	chat.Publish("[info] new participant joined chat")
	defer chat.Publish("[info] participant left chat")
	go func() {
		reader, _ := chat.SubChannel(nil)
		for {
			select {
			case <-closedSession:
				return
			case msg := <-reader:
				if err := session.Send(msg.(string)); err != nil {
					return
				}
			}

		}
	}()
	for {
		if msg, err := session.Recv(); err == nil {
			chat.Publish(msg)
			continue
		}
		break
	}
	close(closedSession)
	log.Println("sockjs session closed")
}
Esempio n. 2
0
File: hub.go Progetto: kellegous/404
func authenticate(s sockjs.Session, ctx *context.Context) (*store.Session, error) {
	val, err := s.Recv()
	if err != nil {
		return nil, err
	}

	var req struct {
		Type  string
		Token string
	}

	if err := json.Unmarshal([]byte(val), &req); err != nil {
		return nil, err
	}

	if req.Type != typeConnect {
		return nil, fmt.Errorf("hub: expected \"connect\" got \"%s\"", req.Type)
	}

	sess, err := auth.SessionFromToken(ctx, req.Token)
	if err != nil {
		return nil, err
	}

	if err := send(s, map[string]string{
		"Type": typeConnect,
	}); err != nil {
		return nil, err
	}

	return sess, nil
}
Esempio n. 3
0
func quoridorHandler(session sockjs.Session) {
	for {
		if msg, err := session.Recv(); err == nil {
			handleMsg(session, msg)
			continue
		}
		break
	}
}
Esempio n. 4
0
func (s *SockJS) Read(session sockjs.Session) {
	for {
		if raw, err := session.Recv(); err == nil {
			s.processMessage(raw, session)
		} else {
			break
		}
	}
}
Esempio n. 5
0
func echoHandler(session sockjs.Session) {
	log.Println("new sockjs session established")
	for {
		if msg, err := session.Recv(); err == nil {
			session.Send(msg)
			continue
		}
		break
	}
	log.Println("sockjs session closed")
}
Esempio n. 6
0
func echoHandler(conn sockjs.Session) {
	log.Println("New connection created")
	for {
		if msg, err := conn.Recv(); err != nil {
			break
		} else {
			if err := conn.Send(msg); err != nil {
				break
			}
		}
	}
	log.Println("Sessionection closed")
}
Esempio n. 7
0
func (ws *Ws) Handler(session sockjs.Session) {
	for {
		if msg, err := session.Recv(); err == nil {
			log.Printf("ws: received: %v", msg)
			message := map[string]interface{}{}
			err = json.Unmarshal([]byte(msg), &message)
			if err != nil {
				respondError(session, err.Error())
				continue
			}
			command, ok := message["cmd"]
			if !ok {
				respondError(session, "`cmd` field must be specified!")
				continue
			}
			commandName, ok := command.(string)
			if !ok {
				respondError(session, "`cmd` must be a string")
				continue
			}
			params, ok := message["params"]
			if !ok {
				respondError(session, "`params` field must be specified!")
				continue
			}
			paramsMap, ok := params.(map[string]interface{})
			if !ok {
				respondError(session, "`params` must be an object!")
				continue
			}
			result, err := ws.Run(commandName, paramsMap)
			if err != nil {
				respondError(session, err.Error())
				continue
			}
			response, err := json.Marshal(result)
			if err != nil {
				panic(err)
			}
			session.Send(string(response))
		} else {
			log.Println(err)
			break
		}
	}
}
Esempio n. 8
0
func echoHandler(session sockjs.Session) {
	for {
		if msg, err := session.Recv(); err == nil {
			session.Send(msg)
			continue
		}
		break
	}
}
Esempio n. 9
0
func sockjsHandler(client sockjs.Session) {
	//new client connected
	for {
		if msg, err := client.Recv(); err == nil {
			//message received
			if strings.HasPrefix(msg, "join") {

				room, ok := clientToRooms[client]

				if ok {
					removeClientFromRoom(room, client)
				}

				roomId, err := strconv.Atoi(strings.TrimPrefix(msg, "join"))

				if err != nil {
					continue
				}

				room, ok = rooms[roomId]

				//create new room if not exists
				if !ok {
					room = ng.NewRoom(roomId, 2)
					rooms[roomId] = room
				}

				clientToRooms[client] = room
				room.AddClient(client)

			} else if room, ok := clientToRooms[client]; ok {
				room.Send(msg, client)
			}
		} else {
			break
		}
	}

	if room, ok := clientToRooms[client]; ok {
		removeClientFromRoom(room, client)
	}
}
Esempio n. 10
0
func echoHandler(session sockjs.Session) {
	log.Println("new sockjs session established")
	var closedSession = make(chan struct{})
	session.Send(session.ID())
	go func() {
		reader, _ := chat.SubChannel(nil)
		for {
			select {
			case <-closedSession:
				return
			case msg := <-reader:
				if err := session.Send(msg.(string)); err != nil {
					return
				}
			}

		}
	}()
	for {
		if msg, err := session.Recv(); err == nil {
			data := &WSDataSchema{}
			buf := bytes.NewBufferString(msg)
			err = json.Unmarshal(buf.Bytes(), data)
			if err == nil {
				_type := data.Type
				_endpoint := data.Endpoint
				_id := data.Id
				if _type == "container" {
					session.Send(_endpoint + _id)
					break
				}
			}
			chat.Publish(msg)
			//session.Send(msg)
			continue
		}
		break
	}
	close(closedSession)
	log.Println("sockjs session closed")
}
Esempio n. 11
0
// sockJSHandler called when new client connection comes to SockJS endpoint.
func (app *Application) sockJSHandler(s sockjs.Session) {

	c, err := newClient(app, s)
	if err != nil {
		logger.ERROR.Println(err)
		return
	}
	defer c.clean()
	logger.INFO.Printf("new SockJS session established with uid %s\n", c.uid())

	for {
		if msg, err := s.Recv(); err == nil {
			err = c.message([]byte(msg))
			if err != nil {
				logger.ERROR.Println(err)
				s.Close(CloseStatus, "error handling message")
				break
			}
			continue
		}
		break
	}
}
Esempio n. 12
0
func Chat(session sockjs.Session) {
	glog.Info("Session started")
	sessionId := session.ID()

	chatSession := &ChatSession{
		Id:      sessionId,
		IsReady: false,
		Session: &session,
	}

	ChatSessions.Set(sessionId, chatSession)

	acceptedTypes := &map[string]string{
		"image/jpeg": ".jpg",
		"image/jpg":  ".jpg",
		"image/png":  ".png",
		"image/gif":  ".gif",
	}

	ticker := time.NewTicker(time.Second)

	// Not too nice, will be refactored later...
	online := func() {
		ready, chatting := ChatSessions.GetNumberOfReadyAndChatting()

		msg := &ChatMessage{
			"event": "online",
			"r":     ready,
			"c":     chatting,
		}
		out, _ := json.Marshal(msg)
		body := string(out)
		session.Send(body)
	}

	go func() {
		for _ = range ticker.C {
			online()
		}
	}()
	online()

	for {
		if msg, err := session.Recv(); err == nil {
			var data ChatMessage
			json.Unmarshal([]byte(msg), &data)

			switch data["event"] {
			case "ready":
				ChatReady(sessionId, data["region"].(string))
			case "typing":
				ChatSessions.Action(func() {
					chatSession.Room.BroadcastOthers(sessionId, "typing", strconv.FormatBool(data["typing"].(bool)))
				})
			case "send":
				ChatSessions.Action(func() {
					chatSession.Room.BroadcastOthers(sessionId, "message", data["message"].(string))
				})
			case "exit":
				ChatSessions.Action(func() {
					glog.Info("Chat session ended")
					chatSession.Room.BroadcastOthers(sessionId, "exit", "")

					for i, _ := range chatSession.Room.Sessions {
						s := chatSession.Room.Sessions[i]
						if s != chatSession {
							s.Room = nil
						}
						//s.IsReady = true
					}
					chatSession.Room = nil
				})
			case "picture":
				glog.Info("Picture received")
				ChatSessions.Action(func() {
					chatSession.Room.BroadcastOthers(sessionId, "picturebefore", "true")
					dataURL, err := dataurl.DecodeString(data["data"].(string))
					if err != nil {
						glog.Error("Problem decoding file: ", err)
					}
					filename := helpers.GetRandomString(8)

					mt := dataURL.ContentType()

					if ext, ok := (*acceptedTypes)[mt]; ok {
						err = ioutil.WriteFile(MediaContent+filename+ext, dataURL.Data, 0644)
						if err != nil {
							glog.Error("Error saving file: ", err)
						}
						chatSession.Room.BroadcastOthers(sessionId, "picture", data["data"].(string))
					}
				})
			}

			continue
		}
		break
	}

	ticker.Stop()

	ChatSessions.Close(sessionId)

	glog.Info("Session closed")
}