Exemplo n.º 1
0
func pushHandler(ws *websocket.Conn) {

	client := &Client{ws, "", "", 0, time.Now()}

	for {
		var f map[string]interface{}

		var err error
		if err = websocket.JSON.Receive(ws, &f); err != nil {
			log.Println("Websocket Disconnected.", err.Error())
			break
		}

		client.LastContact = time.Now()
		log.Println("pushHandler msg: ", f["messageType"])

		messageType, found := f["messageType"]
		if !found {
			// treat it as a ping
			websocket.Message.Send(client.Websocket, "{}")
			continue
		}

		switch messageType {
		case "hello":
			handleHello(client, f)
			break

		case "register":
			handleRegister(client, f)
			break

		case "unregister":
			handleUnregister(client, f)
			break

		case "ack":
			handleAck(client, f)
			break

		default:
			log.Println(" -> Unknown", f)
			break
		}

		saveState()
	}

	log.Println("Closing Websocket!")
	ws.Close()

	// if a client disconnected before completing the handshake
	// it'll have an empty UAID
	if client.UAID != "" {
		gServerState.ConnectedClients[client.UAID].Websocket = nil
	}
}
Exemplo n.º 2
0
func pushHandler(ws *websocket.Conn) {

	client := &Client{ws, "", "", 0, time.Now()}

	for {
		var f map[string]interface{}

		var err error
		if err = websocket.JSON.Receive(ws, &f); err != nil {
			log.Println("Websocket Disconnected.", err.Error())
			break
		}

		client.LastContact = time.Now()
		log.Println("pushHandler msg: ", f["messageType"], len(f), f)

		if len(f) == 0 {
			websocket.Message.Send(client.Websocket, "{}")
			continue
		}

		messageType, found := f["messageType"]
		if !found {
			// treat it as a ping
			f["messageType"] = ""
			messageType = ""
		}
		switch messageType.(type) {
		case string:
			switch strings.ToLower(messageType.(string)) {
			case "hello":
				handleHello(client, f)
				break

			case "register":
				handleRegister(client, f)
				break

			case "unregister":
				handleUnregister(client, f)
				break

			case "ack":
				handleAck(client, f)
				break

			case "ping":
				websocket.Message.Send(client.Websocket, "{}")
				continue

			case "purge":
				verbose("Purging data for ", client.UAID)
				handlePurge(client, f)
				break

			default:
				log.Println(" -> Unknown", f)
				verbose("Please only use 'hello', 'register', 'unregister'",
					"or 'ack' as messageType values.")
				handleError(client, f, 401, "Invalid Command")
				break
			}
			saveState()
		default:
			handleError(client, f, 401, "Invalid Command")
			verbose("Please use only strings as messageTypes")
			break
		}
	}

	log.Println("Closing Websocket!")
	ws.Close()

	// if a client disconnected before completing the handshake
	// it'll have an empty UAID
	if client.UAID != "" {
		gServerState.ConnectedClients[client.UAID].Websocket = nil
	}
}