Web3-Providers

如何使用 shh.subscribe

  • October 3, 2019

我想使用web3-shh功能。我使用了readthedocs(web3-shh)中的範例。除訂閱操作外,一切正常。它引發以下錯誤:

UnhandledPromiseRejectionWarning: Error: Subscriptions are not supported with the HttpProvider.

知道如何處理這個問題嗎?我使用的測試程序是

import Web3            from 'web3';
const uri = process.env.ETH_NODE_URI || 'http://localhost:8545';
var web3 = new Web3(new Web3.providers.HttpProvider(uri));

var identities = [];

Promise.all([
web3.shh.newSymKey().then((id) => {identities.push(id);}),
web3.shh.newKeyPair().then((id) => {identities.push(id);})
]).then(() => {
var subscription = web3.shh.subscribe('messages', {
   symKeyID: identities[0],
   topics: ['0xffaadd11']
}).on('data', console.log);
}).then(() => {
web3.shh.post({
   symKeyID: identities[0], // encrypts using the sym key ID                                                  
   sig: identities[1], // signs the message using the keyPair ID                                              
   topic: '0xffaadd11',
   payload: '0xffffffdddddd1122'
}).then(h => console.log(`Message with hash ${h} was successfuly sent`))
.catch(err => console.log("Error: ", err));
});

我將不勝感激有關如何處理此問題的任何建議。文件中的完整範例也是一個好主意。

正如 Sanjay 上面提到的,您需要 websocket 進行耳語來執行實時通知您傳入消息的功能。

這是一個如何創建 Websocket 提供程序的範例(使用 ethjs,但 web3.js 類似) https://github.com/invisible-college/democracy/blob/master/packages/whisper/src/whisper.js#L23

如果您執行自己的耳語節點,例如 geth 或 status-go 實現(我鼓勵您這樣做,因為其他人的耳語節點將能夠窺探您的密鑰對),您應該使用--wsorigins="mychat"標誌開始它,其中“mychat”只要您在客戶端中創建 websocket 提供程序時選擇相同的值,就可以是任何值。

引用自:https://ethereum.stackexchange.com/questions/76454