Created
February 17, 2017 07:51
-
-
Save florabtw/3d2c492288ac5c6748338f09df7b00a0 to your computer and use it in GitHub Desktop.
WebSocket Client and Server
This file contains hidden or 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
import akka.Done | |
import akka.actor.ActorSystem | |
import akka.http.scaladsl.Http | |
import akka.http.scaladsl.model.StatusCodes | |
import akka.http.scaladsl.model.ws.TextMessage.Strict | |
import akka.http.scaladsl.model.ws.{Message, TextMessage, WebSocketRequest} | |
import akka.stream.scaladsl.{Flow, Keep, Sink, Source, SourceQueue} | |
import akka.stream.{ActorMaterializer, OverflowStrategy} | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.Future | |
import scala.concurrent.duration._ | |
object TestClient extends App { | |
implicit val system = ActorSystem() | |
implicit val materializer = ActorMaterializer() | |
case class MessageOffering(queue: SourceQueue[TextMessage.Strict]) { | |
def offerMessage: Unit = { | |
queue.offer(TextMessage("Bang!")) | |
} | |
} | |
val queue: Source[TextMessage.Strict, SourceQueue[TextMessage.Strict]] = Source.queue[TextMessage.Strict](10, OverflowStrategy.dropNew) | |
val queueSource = queue.mapMaterializedValue { (queue: SourceQueue[Strict]) => | |
val messageOfferer = MessageOffering(queue) | |
system.scheduler.schedule(5.seconds, 1.second) { messageOfferer.offerMessage } | |
} | |
val sink: Sink[Message, Future[Done]] = Sink.foreach { | |
case message: TextMessage.Strict => println(message.text) | |
case _ => | |
} | |
val flow: Flow[Message, Message, Future[Done]] = Flow.fromSinkAndSourceMat(sink, queueSource)(Keep.left) | |
val (upgradeResponse, closed) = Http().singleWebSocketRequest(WebSocketRequest("ws://localhost:8080"), flow) | |
val connected = upgradeResponse.map { upgrade => | |
if (upgrade.response.status == StatusCodes.SwitchingProtocols) { | |
Done | |
} else { | |
throw new RuntimeException("Connection failed!") | |
} | |
} | |
connected.onComplete(println) | |
closed.foreach(_ => println(closed)) | |
} |
This file contains hidden or 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 WebSocket = require('ws'); | |
const wss = new WebSocket.Server({ | |
port: 8080 | |
}); | |
console.log('Running!'); | |
wss.on('connection', function connection(ws) { | |
ws.send('welcome aboard'); | |
console.log("Connection established!"); | |
ws.on('message', function incoming(data, flags) { | |
console.log(data); | |
ws.send('hi there!'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment