stomp.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package stomp
  2. import (
  3. "encoding/json"
  4. "log"
  5. "battlecamp-go/flag"
  6. "github.com/go-stomp/stomp"
  7. )
  8. var stompConnection *stomp.Conn
  9. func getStompConnection() *stomp.Conn {
  10. if stompConnection == nil {
  11. var err error
  12. stompConnection, err = stomp.Dial("tcp", *flag.StompUrl)
  13. if(err != nil) {
  14. log.Printf("Error creating stomp connection error: %v\n", err)
  15. } else {
  16. log.Printf("Created stomp connection to %v", *flag.StompUrl)
  17. }
  18. }
  19. return stompConnection
  20. }
  21. func SendJsonPlayerJoin(topic string, v interface{}) {
  22. sendJson(topic, "vnd.battlecamp.player", v)
  23. }
  24. func SendJsonPlayerUpdate(topic string, v interface{}) {
  25. sendJson(topic, "vnd.battlecamp.update", v)
  26. }
  27. func SendJson(topic string, v interface{}) {
  28. sendJson(topic, "application/json;charset=utf-8", v)
  29. }
  30. func sendJson(topic, contentType string, v interface{}) {
  31. b, _ := json.Marshal(v)
  32. getStompConnection().Send("/topic/go-battlecamp."+topic, contentType, b, stomp.SendOpt.NoContentLength)
  33. }
  34. func Subscribe(topic string) chan *stomp.Message {
  35. result, _ := getStompConnection().Subscribe("/topic/go-battlecamp."+topic, stomp.AckAuto)
  36. return result.C
  37. }