コード例 #1
0
ファイル: webchat.go プロジェクト: wavded/sockjs-go
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")
}
コード例 #2
0
ファイル: hub.go プロジェクト: 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
}
コード例 #3
0
ファイル: hub.go プロジェクト: kellegous/404
func send(s sockjs.Session, data interface{}) error {
	b, err := json.Marshal(data)
	if err != nil {
		return err
	}

	return s.Send(string(b))
}
コード例 #4
0
ファイル: sockjs.go プロジェクト: silentnull/dockership
func (s *SockJS) Read(session sockjs.Session) {
	for {
		if raw, err := session.Recv(); err == nil {
			s.processMessage(raw, session)
		} else {
			break
		}
	}
}
コード例 #5
0
ファイル: routes.go プロジェクト: dnamenon/webshop
func echoHandler(session sockjs.Session) {
	for {
		if msg, err := session.Recv(); err == nil {
			session.Send(msg)
			continue
		}
		break
	}
}
コード例 #6
0
ファイル: handler.go プロジェクト: KingBright/grouplay
func quoridorHandler(session sockjs.Session) {
	for {
		if msg, err := session.Recv(); err == nil {
			handleMsg(session, msg)
			continue
		}
		break
	}
}
コード例 #7
0
ファイル: websocket.go プロジェクト: matobet/verdi
func respondError(session sockjs.Session, message string) {
	result := cmd.Response{
		Status: "error",
		Result: message,
	}
	response, err := json.Marshal(result)
	if err != nil {
		panic(err)
	}
	session.Send(string(response))
}
コード例 #8
0
ファイル: webecho.go プロジェクト: wavded/sockjs-go
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")
}
コード例 #9
0
ファイル: hub.go プロジェクト: kellegous/404
func (h *hub) leave(s sockjs.Session, user *store.User) {
	h.ch <- func() {
		us := h.users[user.Id]
		if us == nil {
			return
		}

		delete(us.sess, s.ID())
		log.Printf("exit: %s", user.Name)
	}
}
コード例 #10
0
ファイル: main.go プロジェクト: nh0815/golem
func wsHandler(session sockjs.Session) {
	log.Println("new sockjs session established")
	go func() {
		reader, _ := broadcaster.SubChannel(nil)
		for {
			status := <-reader
			if err := session.Send(status.(string)); err != nil {
				return
			}
		}
	}()
}
コード例 #11
0
ファイル: server.go プロジェクト: eelcocramer/sockjs-go
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")
}
コード例 #12
0
ファイル: room.go プロジェクト: nickalie/GoSockJSExample
func (this *Room) AddClient(client sockjs.Session) {
	if this.Len() >= this.max {
		return
	} else if indexOf(this.clients, client) == -1 {
		message := "{\"type\":\"userConnected\"}"
		this.sendToAll(message)

		for i := 0; i < this.Len(); i++ {
			client.Send(message)
		}

		this.clients = append(this.clients, client)
	}
}
コード例 #13
0
ファイル: hub.go プロジェクト: kellegous/404
func (h *hub) enter(s sockjs.Session, user *store.User) {
	h.ch <- func() {
		us := h.users[user.Id]
		if us == nil {
			us = &userSession{
				user: user,
				sess: map[string]sockjs.Session{},
			}
			h.users[user.Id] = us
		}
		us.sess[s.ID()] = s
		log.Printf("enter: %s", user.Name)
	}
}
コード例 #14
0
ファイル: player_manager.go プロジェクト: KingBright/grouplay
func Register(session sockjs.Session, oldId string, name string) error {
	if player, ok := FindPlayer(oldId); ok {
		player.Update(session, session.ID(), name)
		fmt.Println("Find an existed player & update it")
		return nil
	} else {
		if p := FindPlayerByName(name); p != nil {
			return NewError("The name is already registered!")
		}
		id := session.ID()
		players[id] = &GamePlayer{id, name, 0, &session, nil, nil, nil, false}
		fmt.Println("Register as new")
		return nil
	}
}
コード例 #15
0
ファイル: websocket.go プロジェクト: matobet/verdi
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
		}
	}
}
コード例 #16
0
ファイル: kite.go プロジェクト: gotao/kite
func (k *Kite) sockjsHandler(session sockjs.Session) {
	defer session.Close(0, "")

	// This Client also handles the connected client.
	// Since both sides can send/receive messages the client code is reused here.
	c := k.NewClient("")
	c.session = session

	go c.sendHub()
	c.wg.Add(1) // with sendHub we added a new listener

	k.callOnConnectHandlers(c)

	// Run after methods are registered and delegate is set
	c.readLoop()

	c.callOnDisconnectHandlers()
	k.callOnDisconnectHandlers(c)
}
コード例 #17
0
ファイル: main.go プロジェクト: nickalie/GoSockJSExample
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)
	}
}
コード例 #18
0
ファイル: messages.go プロジェクト: sandbreaker/photoshare
func receiveMessage(session sockjs.Session) {
	reader, _ := pub.SubChannel(nil)
	for {
		select {
		case msg, ok := <-reader:
			if !ok {
				log.Println("channel closed")
				return
			}
			msg = msg.(*socketMessage)
			if body, err := json.Marshal(msg); err == nil {
				log.Println("message:", string(body))
				if err = session.Send(string(body)); err != nil {
					log.Println(err)
					return
				}
			}
		}
	}
}
コード例 #19
0
ファイル: ws.go プロジェクト: nkwangleiGIT/dockerboard
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")
}
コード例 #20
0
ファイル: handlers.go プロジェクト: rohan1790/centrifugo
// 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
	}
}
コード例 #21
0
ファイル: hub.go プロジェクト: kellegous/404
func accessDenied(s sockjs.Session) error {
	return s.Close(http.StatusForbidden, http.StatusText(http.StatusForbidden))
}
コード例 #22
0
ファイル: server.go プロジェクト: eelcocramer/sockjs-go
func closeHandler(conn sockjs.Session) { conn.Close(3000, "Go away!") }
コード例 #23
0
ファイル: msg.go プロジェクト: KingBright/grouplay
func SendJsonMessage(session sockjs.Session, json string) {
	session.Send(json)
}
コード例 #24
0
ファイル: chat.go プロジェクト: rand99/taillachat
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")
}
コード例 #25
0
ファイル: handler.go プロジェクト: KingBright/grouplay
func handleMsg(session sockjs.Session, msg string) {
	fmt.Println("Message :", msg)
	decoder := json.NewDecoder(strings.NewReader(msg))
	message := new(Message)
	decoder.Decode(message)

	if message.Confirm {
		fmt.Println("Received confirm message : " + msg + " , from " + session.ID())
		return
	}

	switch message.Cmd {
	case CmdCreateGroup:
		if player, ok := FindPlayer(session.ID()); ok {
			decoder := json.NewDecoder(strings.NewReader(message.Msg))
			createInfo := new(CreateGroupMesssage)
			decoder.Decode(createInfo)

			game := GetGame(createInfo.Game)
			if ok, err := player.CreateGroup(game, createInfo.Max, createInfo.AllowSpectator); ok {
				SendStructMessage(session, message.Cmd, struct {
					ID     string `json:"groupId"`
					Hoster bool   `json:"isHoster"`
					OK     bool   `json:"ok"`
				}{ID: player.GroupHosted.ID, Hoster: true, OK: true}, true)
				NotifyGroupListToAll()
			} else {
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
	case CmdJoinGroup:
		if player, ok := FindPlayer(session.ID()); ok {
			decoder := json.NewDecoder(strings.NewReader(message.Msg))
			joinInfo := new(JoinGroupMessage)
			decoder.Decode(joinInfo)

			if ok, err := player.JoinGroup(joinInfo.GroupId); ok {
				SendStructMessage(session, message.Cmd, struct {
					ID string `json:"groupId"`
					OK bool   `json:"ok"`
				}{ID: player.GroupJoined.ID, OK: true}, true)
				NotifyGroupListToAll()
			} else {
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
	case CmdExitGroup:
		if player, ok := FindPlayer(session.ID()); ok {
			decoder := json.NewDecoder(strings.NewReader(message.Msg))
			exitInfo := new(ExitGroupMessage)
			decoder.Decode(exitInfo)

			if ok, err := player.ExitGroup(exitInfo.GroupId); ok {
				SendStructMessage(session, message.Cmd, struct {
					OK bool `json:"ok"`
				}{OK: true}, true)
				NotifyGroupListToAll()
			} else {
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
	case CmdRegister:
		decoder := json.NewDecoder(strings.NewReader(message.Msg))
		registerInfo := new(RegisterMessage)
		decoder.Decode(registerInfo)
		if err := Register(session, registerInfo.ID, registerInfo.Name); err == nil {
			SendStructMessage(session, message.Cmd, struct {
				ID   string `json:"id"`
				Name string `json:"name"`
				OK   bool   `json:"ok"`
			}{session.ID(), registerInfo.Name, true}, true)
			NotifyGroupListToAll()
		} else {
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
		CheckPlayingGame(registerInfo.ID, session.ID())
	case CmdStartGame:
		if player, ok := FindPlayer(session.ID()); ok {
			decoder := json.NewDecoder(strings.NewReader(message.Msg))
			startGameMessage := new(StartGameMessage)
			decoder.Decode(startGameMessage)

			group := player.GroupHosted
			if group == nil {
				err := NewError("You haven't hosted a group.")
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
			if err := StartGame(group, startGameMessage.GroupId); err == nil {
				//Notify all player to action
				group.NotifyPlayer(message.Cmd, struct {
					OK bool `json:"ok"`
				}{true})
			} else {
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
	case CmdGetData:
		if player, ok := FindPlayer(session.ID()); ok {
			if err := GetDataForPlayer(player); err != nil {
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
	case CmdPlayerAction:
		if player, ok := FindPlayer(session.ID()); ok {
			decoder := json.NewDecoder(strings.NewReader(message.Msg))
			dataUpdateMessage := new(DataUpdateMessage)
			decoder.Decode(dataUpdateMessage)

			if player.GroupJoined != nil {
				if err := UpdateData(player, player.GroupJoined, dataUpdateMessage.Action, dataUpdateMessage.Data); err == nil {
					SendStructMessage(session, message.Cmd, struct {
						OK bool `json:"ok"`
					}{true}, true)
				} else {
					SendErrorMessage(session, message.Cmd, err.Error(), false, true)
				}
			} else {
				err := NewError("You are not playing in the group")
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
	case CmdQuitGame:
		if player, ok := FindPlayer(session.ID()); ok {
			NotifyGroupListToOne(player)
		}
	case CmdStopGame:
		if player, ok := FindPlayer(session.ID()); ok {
			if player.GroupHosted != nil {
				if player.GroupHosted.Playing {
					player.GroupHosted.Playing = false
					player.InGame = false
					for _, p := range player.GroupHosted.Players {
						p.InGame = false
					}
					player.GroupHosted.NotifyAllExcept(CmdHostStop, "", player)
				}
			}
			NotifyGroupListToOne(player)
		}
	case CmdGetGameList:
		SendStructMessage(session, message.Cmd, GetGameList(), true)
	case CmdSpectateGame:
		if player, ok := FindPlayer(session.ID()); ok {
			decoder := json.NewDecoder(strings.NewReader(message.Msg))
			spectInfo := new(SpectateGroupMessage)
			decoder.Decode(spectInfo)

			if ok, err := player.SpectateGame(spectInfo.GroupId); ok {
				player.Index = 5
				NotifyGroupListToSpectator(player)
				SendStructMessage(session, message.Cmd, struct {
					ID string `json:"groupId"`
					OK bool   `json:"ok"`
				}{ID: player.GroupSpectating.ID, OK: true}, true)
			} else {
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}
		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}
	case CmdStopSpectating:
		if player, ok := FindPlayer(session.ID()); ok {
			if player.GroupSpectating != nil {
				for i, spectator := range player.GroupSpectating.Spectators {
					if player == spectator {
						player.GroupSpectating.Spectators = append(player.GroupSpectating.Spectators[:i], player.GroupSpectating.Spectators[i+1:]...)
						player.GroupSpectating = nil
						player.InGame = false
						player.Index = 0

						NotifyGroupListToSpectator(player)
						return
					}
				}
				err := NewError("Not found the spectator ")
				SendErrorMessage(session, message.Cmd, err.Error(), false, true)
			}

		} else {
			err := NewError("No user found with id " + session.ID())
			SendErrorMessage(session, message.Cmd, err.Error(), false, true)
		}

	}
}