Skip to content

Instantly share code, notes, and snippets.

@vishalxl
Last active February 18, 2023 04:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishalxl/e16c066408f45d39e92b647e9766efa1 to your computer and use it in GitHub Desktop.
Save vishalxl/e16c066408f45d39e92b647e9766efa1 to your computer and use it in GitHub Desktop.
Get Nostr Events from a Relay
import 'dart:io';
import 'dart:convert';
String serverUrl = 'wss://nostr-pub.wellorder.net';
var userPublickey = "3235036bd0957dfb27ccda02d452d7c763be40c91a1ac082ba6983b25238388c";
var userSubReq = '["REQ","latest",{ "authors": ["$userPublickey"], "limit": 5 } ]';
class EventData {
String id;
String pubkey;
String content;
EventData(this.id, this.pubkey, this.content);
factory EventData.fromJson(dynamic json) {
return EventData(json['id'] as String, json['pubkey'] as String, json['content'] as String);
}
@override
String toString() {
return 'id : $id\nAuthor : $pubkey\nMessage: $content\n';
}
}
class Event {
String event;
String id;
EventData eventData;
Event(this.event, this.id, this.eventData);
factory Event.fromJson(dynamic json) {
if( json.length < 3) {
String e = "";
if(json.length > 1) e = json[0];
else e = "";
return Event(e,"",EventData("empty","",""));
}
else
return Event(json[0] as String, json[1] as String, EventData.fromJson(json[2]) );
}
@override
String toString() {
return '$eventData';
}
}
void main() {
Future<WebSocket> fws = WebSocket.connect(serverUrl);
List<String> events = [];
fws.then((WebSocket ws) {
ws.listen(
(d) { events.add( d); },
onError: (e) { print("error"); print(e); },
onDone: () { print('in onDone'); ws.close() ; exit(0);}
);
ws.add(userSubReq);
});
Future.delayed(const Duration(milliseconds: 2000), () {
for( int i = 0; i < events.length; i++) {
//print('Event number $i: ${events[i]}');
Event e = Event.fromJson(jsonDecode(events[i]));
print('-------+\n$e');
}
exit(0);
});
}
@vishalxl
Copy link
Author

vishalxl commented Jul 7, 2022

This works:

import 'dart:io';

String socketServerUrl = 'wss://ws.postman-echo.com/raw';
//String socketServerUrl = 'ws://echo.FAILS.org/';

void main() {

  Future<WebSocket> futureWebSocket = WebSocket.connect(socketServerUrl);
  futureWebSocket.then((WebSocket ws) {
   
    WebSocket  webSocket = ws;
    print(webSocket.readyState);

    webSocket.listen(
        (d) { print('received: $d'); },
        onError: (e) { print("error"); print(e); }, 
        onDone: () => print("done")
    );

    // send message
    print('sent hello world');
    webSocket.add('hello world');

    Future.delayed(const Duration(milliseconds: 5000), () {
      print('Closing connection after 5 second future delay.');
      ws.close();
    });
  
    
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment