Created
July 11, 2021 12:28
-
-
Save qmzik/c51e450b34da677c7517bd02b6e51990 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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