I am trying to develop a websocket server using Scala, Akka and Play Framework 2.7.
I am sending 2 different “Sec-WebSocket-Protocol” in the request. Say(“abc1.0”,“abc2.0”)
Consider the server accepts only the protocol “abc1.0”.
I want the server to process the request and return the response if the request header Sec-WebSocket-Protocol contains “abc1.0”. If not it should send a response with “Sec-WebSocket-Protocol” header as “abc1.0”.
How can I set the “Sec-WebSocket-Protocol” header in the response header?
Please check the code below and help us to solve this use case.
Server code:
def chatServer(userId: String) = WebSocket.acceptOrResult[String, String] { request =>
Future.successful {
AuthenticationService.doBasicAuthentication(userId, request.headers) match {
case Results.Ok =>
Right(ActorFlow.actorRef { out =>
ChatServiceActor.props(out, userId, ba.monitorActor, ba.cacheActor)
})
case Results.Unauthorized =>
Left(Unauthorized.withHeaders(("Sec-WebSocket-Protocol", "abc1.0")))
}
}
}
Client Request:
val (upgradeResponse, closed) =Http().singleWebSocketRequest(WebSocketRequest("ws://localhost:9000/chatServer/user1",
extraHeaders = Seq(Authorization(BasicHttpCredentials(userId, "password@123")),SecWebSocketProtocol.create("abc1.0","abc2.0"))), flow)
val connected = upgradeResponse.map { upgrade =>
if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
Done
} else {
throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
}
}