我正在使用2个TCP连接连接到供应商API。在一个连接上,我发出同步请求;第二个连接用于API推送响应。
我目前正在使用ganymed-ssh-2库与服务器建立两个连接。我在建立连接时执行握手:在建立同步连接时,我收到一个令牌,我用它在异步通道上进行身份验证。我目前只是打印出经过身份验证后在异步通道上收到的所有消息。
我应该采取哪些步骤来继续在同步通道上发出请求(此时只使用stdin),并继续从stdout上的异步通道打印响应?我不确定我是否应该使用Actor(我很难找到一个可以从输入流中读取并相应地解析消息的Actor的示例),或者是否有一些其他Scala-esque构造我应该使用。
class SyncConnection {
def connect(): String = {
// Establish connection
...
val out = new PrintStream(outputStream)
val in = new BufferedSource(inputStream).getLines()
// Make login request, receive token
out.println("loginRequest")
out.flush()
val token = in.next()
token
}
}
class AsyncConnection {
def connect(token: String) {
// Establish connection
...
val in = new BufferedSource(inputStream).getLines()
val out = new PrintStream(outputStream)
// Authenticate using token
out.println(token)
out.flush()
// Print all messages received on input stream
for (line <- in) println(line)
}
}
答案 0 :(得分:0)
我最终使用组合或常规Scala actor和Akka actor来完成此任务。演员可以轻松地将消息传递给彼此以执行握手:
我将2个常规演员连接到两个连接的输入流:
class InputStreamReaderActor(lines: Iterator[String], listener: ActorRef) extends Actor {
def act() {
for (line <- lines) {
listener ! line
}
}
}
这将读取两个连接上的任何传入消息,并立即将响应转发给侦听器actor。这些听众演员看起来如下:
class SyncListenerActor() extends Actor {
def receive: Receive = {
// respond to incoming messages
}
}
为了对连接发出请求,我只是将每个连接的输出流挂钩到Akka actor:
class SyncRequestorActor(out: PrintStream) extends Actor {
def receive: Receive = {
//
}
def sendRequest(request: String) {
println("Making request: " + request)
out.println(request)
out.flush()
}
}