Skip to content

Instantly share code, notes, and snippets.

@chrylarson
Last active January 14, 2022 17:15
Show Gist options
  • Save chrylarson/15d69101b29166683a538082a64c2a1c to your computer and use it in GitHub Desktop.
Save chrylarson/15d69101b29166683a538082a64c2a1c to your computer and use it in GitHub Desktop.
example of web socket in React.js
## Scala
val topic = "raw"
val kafkaSource: Source[ConsumerRecord[String, String], Consumer.Control] = // listen to our topic with our settings, until the program is exited
Consumer.plainSource(consumerSettings, Subscriptions.topics(topic))
...
val webSocketWriteLogic: Source[Message, NotUsed] =
kafkaSource.via(kafkaRecordToSensorData).toMat(BroadcastHub.sink)(Keep.right).run()
...
# Akka Actor
override def onMessage(msg: Command): Behavior[Command] = {
msg match {
case RequestStream(requestId, replyTo) =>
context.log.warn("Requesting Stream")
replyTo ! RespondStream(requestId, Flow.fromSinkAndSource(Sink.ignore, webSocketWriteLogic))
this
...
## JavaScript
import ReconnectingWebSocket from 'reconnecting-websocket';
const URL = 'ws://localhost:8080/realtime'
ws = new ReconnectingWebSocket(URL)
componentDidMount() {
this.ws.onopen = () => {
// on connecting, do nothing but log it to the console
console.log('connected')
}
this.ws.onmessage = evt => {
// on receiving a message, add it to the list of messages
if ('data' in evt) {
const message = JSON.parse(evt.data)
if ('Error' in message) {
console.log('Server: JSON Error');
} else {
this.addMessage(message)
}
}
}
this.ws.onclose = () => {
console.log('disconnected')
// automatically try to reconnect on connection loss
}
this.ws.onerror = function (err) {
console.error('Socket encountered error: Closing socket');
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment