Skip to content

Instantly share code, notes, and snippets.

@qmzik
Created July 11, 2021 12:28
Show Gist options
  • Save qmzik/c51e450b34da677c7517bd02b6e51990 to your computer and use it in GitHub Desktop.
Save qmzik/c51e450b34da677c7517bd02b6e51990 to your computer and use it in GitHub Desktop.
const helloSocket = new Observable<string>((subscriber) => {
// Open a socket.
const socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => {
// Once it's open, send some text.
socket.send('Hello, World!');
};
socket.onmessage = (e) => {
// When it echoes the text back (in the case of this particular server)
// notify the consumer.
subscriber.next(e.data);
};
socket.onclose = (e) => {
// Oh! we closed!
if (e.wasClean) {
// ...because the server said it was done.
subscriber.complete();
} else {
// ...because of something bad. Maybe we lost network or something.
subscriber.error(new Error('Socket closed dirty!'));
}
};
});
// Start the websocket and log the echoes
helloSocket.subscribe({
next: console.log,
complete: () => console.log('server closed'),
error: console.error,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment