You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.2 KiB

  1. package net
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. shell "github.com/ipfs/go-ipfs-api"
  7. "github.com/vocdoni/go-dvote/types"
  8. )
  9. type PubSubHandle struct {
  10. c *types.Connection
  11. s *shell.PubSubSubscription
  12. }
  13. func PsSubscribe(topic string) *shell.PubSubSubscription {
  14. sh := shell.NewShell("localhost:5001")
  15. sub, err := sh.PubSubSubscribe(topic)
  16. if err != nil {
  17. fmt.Fprintf(os.Stderr, "error: %s", err)
  18. os.Exit(1)
  19. }
  20. return sub
  21. }
  22. func PsPublish(topic, data string) error {
  23. sh := shell.NewShell("localhost:5001")
  24. err := sh.PubSubPublish(topic, data)
  25. if err != nil {
  26. return err
  27. }
  28. return nil
  29. }
  30. func (p *PubSubHandle) Init() error {
  31. p.s = PsSubscribe(p.c.Topic)
  32. return nil
  33. }
  34. func (p *PubSubHandle) Listen(reciever chan<- types.Message, errors chan<- error) {
  35. var psMessage *shell.Message
  36. var msg types.Message
  37. var err error
  38. for {
  39. psMessage, err = p.s.Next()
  40. if err != nil {
  41. errors <- err
  42. fmt.Fprintf(os.Stderr, "recieve error: %s", err)
  43. }
  44. msg.Topic = p.c.Topic
  45. msg.Data = psMessage.Data
  46. msg.Address = psMessage.From.String()
  47. msg.TimeStamp = time.Now()
  48. reciever <- msg
  49. }
  50. }
  51. func (p *PubSubHandle) Send(data []byte, errors chan<- error) {
  52. err := PsPublish(p.c.Topic, string(data))
  53. if err != nil {
  54. errors <- err
  55. }
  56. }