Skip to content

Instantly share code, notes, and snippets.

@Nuhvi
Last active June 24, 2022 07:19
Show Gist options
  • Save Nuhvi/5a152d4ad20a8e240f9fee5accc50127 to your computer and use it in GitHub Desktop.
Save Nuhvi/5a152d4ad20a8e240f9fee5accc50127 to your computer and use it in GitHub Desktop.
Slashtags SDK quick communication setup
import { SDK } from '@synonymdev/slashtags-sdk';
const sdkA = await SDK.init({
persist: false, // No storage needed for this demo
primaryKey: Buffer.from('a'.repeat(64)), // Keep primary key consistent
});
console.log("Alice's DHT bootstrapped"); // Bootstrapping DHT takes some time.
const alice = sdkA.slashtag({ name: 'alice' });
alice.listen();
console.log('Alice is listening on: ' + alice.url);
alice.on('connection', (conn, peerInfo) => {
console.log('Alice got connection from: ' + peerInfo.slashtag.url);
conn.on('data', (data) => {
// Idiomatic way is to create and register a custom [SlashProtocol](https://github.com/synonymdev/slashtags/blob/master/packages/slashtag/README.md#example),
// but we can just wing it just like in websocket.
try {
const request = JSON.parse(data.toString());
console.log('Alice got request: ', request.payload);
conn.write(Buffer.from(JSON.stringify({ payload: 'pong' })));
} catch (error) {
// not our business
}
});
});
const sdkB = await SDK.init({
persist: false, // No storage needed for this demo
primaryKey: Buffer.from('b'.repeat(64)), // Keep primary key consistent
});
console.log("Bob's DHT bootstrapped"); // Bootstrapping DHT takes some time.
const bob = sdkB.slashtag({ name: 'bob' });
console.log('connecting to Alice at: ' + alice.url);
const { connection, peerInfo } = await bob.connect(alice.url);
console.log(
'Bob connected to alice: ' +
(peerInfo.slashtag.url.toString() === alice.url.toString()).toString(),
);
connection.on('data', (data) => {
try {
const response = JSON.parse(data.toString());
console.log('Bob got response: ', response.payload);
gracefulClose();
} catch (error) {
// not our business
}
});
connection.write(Buffer.from(JSON.stringify({ payload: 'ping' })));
function gracefulClose() {
sdkA.close();
sdkB.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment