使用 ws和ipc 协议进行消息订阅

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
65
const Net = require('net');
const Web3 = require("web3");

// 设置 Provider, 使用 Infura, 自建 Rinkeby 节点的 ws/ipc 方式
//const wsProvider = new Web3.providers.WebsocketProvider("wss://rinkeby.infura.io/ws");
const wsProvider = new Web3.providers.WebsocketProvider("ws://www.xxx.com:1222", {
headers: {Origin: "http://www.xxx.com"}
});
//const wsProvider = new Web3.providers.IpcProvider("/Users/xxx/rinkeby/data/geth.ipc", Net);

// 设置 provider 给 web3
const web3 = new Web3(wsProvider);

// 订阅 syncing 状态, 测试没有成功, 无法获取数据
const subscriptionSync = web3.eth.subscribe("syncing", (err, sync) => {
//console.log("\n\n\nSyncing ==== %j ", sync, err);
})
.on("data", sync => {
console.log("Syncing Data %j ", sync);
})
.on("changed", isSyncing => {
console.log("Syncing isSyncing %s", isSyncing);
})
.on("error", err => {
console.error("Syncing Error: ", err);
});

// 订阅 block 块状态
const subscriptionBlock = web3.eth.subscribe("newBlockHeaders", (err, blockHeader) => {
//console.log("\n\n\nBlockHeader ==== %j ", blockHeader, err);
})
.on("data", blockHeader => {
console.log("Block Data %j ", blockHeader);
})
.on("error", err => {
console.error("Block Error: ", err);
});

// 订阅 event 日志信息
const subscriptionLog = web3.eth.subscribe("logs", {}, (err, log) => {
//console.log("\n\n\nLogs ==== %j ", log, err);
})
.on("data", log => {
// 本信息包含 pending 状态的数据, 出错后更正的数据
console.log("Logs Data %j", log);
})
.on("changed", log => {
// 由于上面包含 pending 状态的信息, 那么挖矿后可能出现某些交易未成功, 导致原有 pending 状态的数据有变化,
// 那么在此重新发送有问题的数据并且标记为 removed true, 同时更新后的数据将仍由上面的 data 事件捕获.
console.log("Logs Changed %j", log);
})
.on("error", err => {
console.error("Logs Error: ", err);
});

// 监听 pending 状态的交易.
const subscriptionPending = web3.eth.subscribe("pendingTransactions", (err, transactionHash) => {
//console.log("\n\n\nPending ==== %s ", transactionHash, err);
})
.on("data", transactionHash => {
console.log("Pending Data %s", transactionHash);
})
.on("error", err => {
console.error("Pending Error: ", err);
});
Donate - Support to make this site better.
捐助 - 支持我让我做得更好.