Send message

This commit is contained in:
Franck Royer 2021-07-28 12:45:41 +10:00
parent 3f6497634f
commit 7c5382dfff
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
2 changed files with 62 additions and 1 deletions

View File

@ -1,7 +1,9 @@
import './App.css';
import { getStatusFleetNodes, Waku } from 'js-waku';
import { getStatusFleetNodes, Waku, WakuMessage } from 'js-waku';
import * as React from 'react';
const ContentTopic = `/relay-guide/1/chat/proto`;
function App() {
const [waku, setWaku] = React.useState(undefined);
const [wakuStatus, setWakuStatus] = React.useState('NotStarted');
@ -21,10 +23,21 @@ function App() {
});
}, [waku, wakuStatus]);
const sendMessageOnClick = () => {
if (wakuStatus !== 'Ready') return;
sendMessage('Here is a message', waku).then(() =>
console.log('Message sent')
);
};
return (
<div className="App">
<header className="App-header">
<p>{wakuStatus}</p>
<button onClick={sendMessageOnClick} disabled={wakuStatus !== 'Ready'}>
Send Message
</button>
</header>
</div>
);
@ -36,3 +49,8 @@ async function bootstrapWaku(waku) {
const nodes = await getStatusFleetNodes();
await Promise.all(nodes.map((addr) => waku.dial(addr)));
}
async function sendMessage(message, waku) {
const wakuMessage = await WakuMessage.fromUtf8String(message, ContentTopic);
await waku.relay.send(wakuMessage);
}

View File

@ -39,3 +39,46 @@ import { getStatusFleetNodes } from 'js-waku';
const nodes = await getStatusFleetNodes();
await Promise.all(nodes.map((addr) => waku.dial(addr)));
```
# Send messages
We are now ready to send message.
Let's start by sending simple strings as messages.
To send a message, we need to wrap the message in a `WakuMessage`.
When using a basic string payload, we can just use the `WakuMessage.fromUtf8String` helper:
```js
import { WakuMessage } from 'js-waku';
const wakuMessage = await WakuMessage.fromUtf8String(message, `/relay-guide/1/chat/proto`);
```
Then, we use the `relay` module to send the message to our peers,
the message will then be relayed to the rest of the network thanks to Waku Relay:
```js
import { WakuMessage } from 'js-waku';
const wakuMessage = await WakuMessage.fromUtf8String(message, `/relay-guide/1/chat/proto`);
await waku.relay.send(wakuMessage)
```
So far, we have:
```js
import { getStatusFleetNodes, Waku, WakuMessage } from 'js-waku';
const wakuNode = await Waku.create();
import { getStatusFleetNodes } from 'js-waku';
const nodes = await getStatusFleetNodes();
await Promise.all(nodes.map((addr) => waku.dial(addr)));
const wakuMessage = await WakuMessage.fromUtf8String(message, `/relay-guide/1/chat/proto`);
await waku.relay.send(wakuMessage)
```