Skip to content

Websocket

Eleazar Garrido edited this page Oct 7, 2018 · 16 revisions

WebSockets make possible receiving notifications when a transaction or event occurs in the blockchain. The notification is received in real time without having to poll the API waiting for a reply.

Subscribe block

The block channel notifies for every new block. The message contains the block information.

package main

import (
	"fmt"
	"github.com/proximax-storage/nem2-sdk-go/sdk"
)

const	baseUrl     = "http://catapult.internal.proximax.io:3000"

func main() {

	ws, err := sdk.NewConnectWs(baseUrl)
	if err != nil {
		panic(err)
	}

	fmt.Println("websocket negotiated uid:", ws.Uid)
	d, _ := ws.Subscribe.Block()

	for {
		data := <-d.ChIn
		ch := data.(*sdk.BlockInfo)
		fmt.Printf("Block received with height: %v \n", ch.Height)
	}
}

Subscribe confirmedAdded

The confirmedAdded channel notifies when a transaction related to an address is included in a block. The message contains the transaction.

const (
	baseUrl     = "http://catapult.internal.proximax.io:3000"
	networkType = sdk.MijinTest
	privateKey  = "24CEC4F2DD1A28EBB2C0CF6D4D181BA2C0F1E215C42B9059EEFB65B1FAEE1B99"
)

acc, err := sdk.NewAccount(privateKey, networkType)
b, _ := ws.Subscribe.ConfirmedAdded(acc.Address.Address)
go func() {
	for {
		data := <-b.ChIn
		ch := data.(sdk.Transaction)
		fmt.Printf("ConfirmedAdded Tx Hash: %v \n", ch.GetAbstractTransaction().Hash)
		//b.Unsubscribe()
		fmt.Println("Successful transfer!")
	}
}()