-
Notifications
You must be signed in to change notification settings - Fork 2
/
ExampleNewHeaderSubscription.cs
64 lines (50 loc) · 2.12 KB
/
ExampleNewHeaderSubscription.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using Nethereum.JsonRpc.WebSocketStreamingClient;
using Nethereum.RPC.Reactive.Eth.Subscriptions;
using System;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Nethereum.Templates.WebSocketStreaming
{
internal class ExampleNewHeaderSubscription
{
private readonly string url;
StreamingWebSocketClient client;
public ExampleNewHeaderSubscription(string url)
{
this.url = url;
}
public async Task SubscribeAndRunAsync()
{
if (client == null)
{
client = new StreamingWebSocketClient(url);
client.Error += Client_Error;
}
var blockHeaderSubscription = new EthNewBlockHeadersObservableSubscription(client);
blockHeaderSubscription.GetSubscribeResponseAsObservable().Subscribe(subscriptionId =>
Console.WriteLine("Block Header subscription Id: " + subscriptionId));
blockHeaderSubscription.GetSubscriptionDataResponsesAsObservable().Subscribe(block =>
Console.WriteLine("New Block: " + block.BlockHash)
, exception =>
{
Console.WriteLine("BlockHeaderSubscription error info:" + exception.Message);
});
blockHeaderSubscription.GetUnsubscribeResponseAsObservable().Subscribe(response =>
Console.WriteLine("Block Header unsubscribe result: " + response));
await client.StartAsync();
await blockHeaderSubscription.SubscribeAsync();
Thread.Sleep(20000);
await blockHeaderSubscription.UnsubscribeAsync();
Console.WriteLine("Finished after 20000 miliseconds");
}
private async void Client_Error(object sender, Exception ex)
{
Console.WriteLine("Client Error restarting...");
// ((StreamingWebSocketClient)sender).Error -= Client_Error;
((StreamingWebSocketClient)sender).StopAsync().Wait();
//Restart everything
await SubscribeAndRunAsync();
}
}
}