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.

69 lines
1.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package core_client
  2. import (
  3. "github.com/gorilla/websocket"
  4. "github.com/tendermint/tendermint/rpc"
  5. "net/http"
  6. )
  7. // A websocket client subscribes and unsubscribes to events
  8. type WSClient struct {
  9. host string
  10. conn *websocket.Conn
  11. }
  12. // create a new connection
  13. func NewWSClient(addr string) *WSClient {
  14. return &WSClient{
  15. host: addr,
  16. }
  17. }
  18. func (wsc *WSClient) Dial() (*http.Response, error) {
  19. dialer := websocket.DefaultDialer
  20. rHeader := http.Header{}
  21. conn, r, err := dialer.Dial(wsc.host, rHeader)
  22. if err != nil {
  23. return r, err
  24. }
  25. wsc.conn = conn
  26. return r, nil
  27. }
  28. // subscribe to an event
  29. func (wsc *WSClient) Subscribe(eventid string) error {
  30. return wsc.conn.WriteJSON(rpc.WSRequest{
  31. Type: "subscribe",
  32. Event: eventid,
  33. })
  34. }
  35. // unsubscribe from an event
  36. func (wsc *WSClient) Unsubscribe(eventid string) error {
  37. return wsc.conn.WriteJSON(rpc.WSRequest{
  38. Type: "unsubscribe",
  39. Event: eventid,
  40. })
  41. }
  42. type WSMsg struct {
  43. Data []byte
  44. Error error
  45. }
  46. // returns a channel from which messages can be pulled
  47. // from a go routine that reads the socket.
  48. // if the ws returns an error (eg. closes), we return
  49. func (wsc *WSClient) Read() chan *WSMsg {
  50. ch := make(chan *WSMsg)
  51. go func() {
  52. for {
  53. _, p, err := wsc.conn.ReadMessage()
  54. ch <- &WSMsg{p, err}
  55. if err != nil {
  56. return
  57. }
  58. }
  59. }()
  60. return ch
  61. }