scala-stomp-client-demo/stompTest.sc
2020-08-13 20:21:11 +05:30

108 lines
2.5 KiB
Scala
Executable File

#!/usr/bin/env amm
import $repo.`https://jitpack.io`
import $ivy.`com.github.gim-.java-stomp-ws:stomp-client-ws:v1.0`
import eu.mivrenik.stomp.StompFrame
import eu.mivrenik.stomp.client.StompClient
import eu.mivrenik.stomp.client.listener.StompMessageListener
import java.net.URI
import scala.util.Try
import scala.util.Success
import scala.util.Failure
import scala.collection.JavaConverters._
import org.java_websocket.drafts.Draft._
import org.java_websocket.drafts.Draft_6455
import java.{util => ju}
import ju.HashMap
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._
@main
def run(
username: String = "user",
password: String = "password",
host: String = "localhost",
port: Int = 8080,
endpoint: String = "ws"
) = {
val msg =
s"""{"toUser":"admin","fromUser":"$username","messageContent":"hello"}"""
val usernameAndPassword = s"$username:$password"
val encoded =
ju.Base64.getEncoder.encodeToString(usernameAndPassword.getBytes())
val headers = new ju.HashMap[String, String]
headers.put("Authorization", s"Basic $encoded")
val stompSocket = new StompClient(
URI.create(s"ws://$host:$port/$endpoint"),
new Draft_6455(),
headers,
60
)
val t = new Thread(() => {
val res = Try(stompSocket.connectBlocking())
println(res)
res match {
case Success(value) => {
println("Connected")
stompSocket ? (
"/user/queue/ping",
(stompFrame: StompFrame) => {
println("Server message: " + stompFrame.getBody())
}
)
val x = stompSocket ? (
"/user/queue/reply",
(stompFrame: StompFrame) => {
println("Server message: " + stompFrame.getBody())
stompSocket.close()
}
)
stompSocket ! "/app/ping"
stompSocket ! ("/app/message-test", Some(msg))
}
case Failure(exception) => { println(exception.getMessage()) }
}
})
t.start()
Thread.sleep(1000)
t.stop()
}
/**
* Extension methods for Java Stomp Client
*
* @param client
*/
implicit class RichStompClient(client: StompClient) {
/**
* alias for send
*
* @param dest
* @param message
*/
def !(dest: String, message: Option[String] = None) =
message.fold(client.send(dest, ""))(m => client.send(dest, m))
/**
* alias for subscribe
*
* @param route
* @param listener
* @return StompSubscription
*/
def ?(route: String, listener: StompMessageListener) =
client.subscribe(route, listener)
}