我在web3版本1.0.0-beta.27
上,我正在运行一个私有的以太坊区块链用于测试目的。区块链是挖掘并有两个用户,现在我想subscribe
到区块链中的事件并执行一些操作。代码如下:
var Web3 = require("web3");
var ether_port = 'http://localhost:8545'
var web3 = new Web3(new Web3.providers.HttpProvider(ether_port));
web3.eth.subscribe("pendingTransactions"
, function(err, result){
if (err){ console.log(err) }
else { console.log("result: ", result) }
});
我有类似的东西:
Error: The current provider doesn't support subscriptions: HttpProvider
at Subscription.subscribe
从某种意义上说,当我在web3.eth.subscribe
控制台上执行node.js
时,我得到的结果并不令人惊讶:
{ [Function] call: undefined }
即使web3-1.0.0
的文档声明可以使用该函数:https://web3js.readthedocs.io/en/1.0/web3-eth-subscribe.html。
n
分数对链进行ping操作。正如错误所示,pub / sub不能通过HTTP获得。但是,您可以通过WS使用它。因此,您引用的文档不是100%错误,它只是省略了代码的提供程序部分。
尝试使用Web套接字连接启动节点(geth --ws --wsport 8545 ...
,假设您正在使用geth
),并更改为WebsocketProvider
。
var Web3 = require("web3");
var ether_port = 'ws://localhost:8545'
var web3 = new Web3(new Web3.providers.WebsocketProvider(ether_port));
web3.eth.subscribe("pendingTransactions"
, function(err, result){
if (err){ console.log(err) }
else { console.log("result: ", result) }
});
查看关于此discussion ticket的第4条评论。
使用附加的JS控制台打开它的更好方法
您可以使用> geth attach'ipc path'附加(即在我的情况下是/home/dev/.ethereum/geth.ipc)
之后,您将连接到运行geth节点并使用管理API ..现在您可以使用
admin.startWS(“localhost”,“端口号”)
当你想关闭连接时,你可以使用下面的命令
admin.stopWS()
关心开发