tendermint/rpc/core_client/ws_client.go

74 lines
1.5 KiB
Go
Raw Normal View History

2015-04-20 02:13:04 -07:00
package core_client
import (
2015-06-09 23:17:19 -04:00
"github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/gorilla/websocket"
rpctypes "github.com/tendermint/tendermint/rpc/types"
2015-04-20 02:13:04 -07:00
"net/http"
)
// A websocket client subscribes and unsubscribes to events
type WSClient struct {
host string
conn *websocket.Conn
}
// create a new connection
func NewWSClient(addr string) *WSClient {
return &WSClient{
host: addr,
}
}
2015-04-20 14:00:19 -07:00
func (wsc *WSClient) Dial() (*http.Response, error) {
2015-04-20 02:13:04 -07:00
dialer := websocket.DefaultDialer
rHeader := http.Header{}
2015-04-20 14:00:19 -07:00
conn, r, err := dialer.Dial(wsc.host, rHeader)
2015-04-20 02:13:04 -07:00
if err != nil {
2015-04-20 14:00:19 -07:00
return r, err
2015-04-20 02:13:04 -07:00
}
wsc.conn = conn
2015-04-20 14:00:19 -07:00
return r, nil
2015-04-20 02:13:04 -07:00
}
// subscribe to an event
func (wsc *WSClient) Subscribe(eventid string) error {
2015-07-23 17:06:38 -07:00
return wsc.conn.WriteJSON(rpctypes.RPCRequest{
JSONRPC: "2.0",
Id: "",
Method: "subscribe",
Params: []interface{}{eventid},
2015-04-20 02:13:04 -07:00
})
}
// unsubscribe from an event
func (wsc *WSClient) Unsubscribe(eventid string) error {
2015-07-23 17:06:38 -07:00
return wsc.conn.WriteJSON(rpctypes.RPCRequest{
JSONRPC: "2.0",
Id: "",
Method: "unsubscribe",
Params: []interface{}{eventid},
2015-04-20 02:13:04 -07:00
})
}
2015-04-20 14:00:19 -07:00
type WSMsg struct {
Data []byte
Error error
}
// returns a channel from which messages can be pulled
// from a go routine that reads the socket.
// if the ws returns an error (eg. closes), we return
func (wsc *WSClient) Read() chan *WSMsg {
ch := make(chan *WSMsg)
go func() {
for {
_, p, err := wsc.conn.ReadMessage()
ch <- &WSMsg{p, err}
if err != nil {
return
}
}
}()
return ch
}