2014-04-03 68 views
0

我正在測試Play Framework 2.1中的WebSocket代碼。我的方法是獲取用於實際Web套接字的迭代器/枚舉器對,並且只是測試將數據推入並拉出數據。播放2.1:來自枚舉器的等待結果

不幸的是,我只是無法弄清楚如何從一個枚舉器中獲取數據。現在我的代碼看起來大致是這樣的:

val (in, out) = createClient(FakeRequest("GET", "/myendpoint")) 

in.feed(Input.El("My input here")) 
in.feed(Input.EOF) 

//no idea how to get data from "out" 

至於我可以告訴大家,讓數據從一個枚舉的唯一方式是通過iteratee。但我無法弄清楚如何等待,直到我得到來自枚舉器的完整字符串列表。我想要的是List[String],而不是Future[Iteratee[A,String]]Expectable[Iteratee[String]]或另一個Iteratee[String]。文檔充其量是令人困惑的。

我該怎麼做?

+0

你能添加'createClient'方法的(簡化的)內容? – EECOLOR

回答

-1

可以消耗一個Enumerator這樣的:

val out = Enumerator("one", "two") 

    val consumer = Iteratee.getChunks[String] 

    val appliedEnumeratorFuture = out.apply(consumer) 

    val appliedEnumerator = Await.result(appliedEnumeratorFuture, 1.seconds) 

    val result = Await.result(appliedEnumerator.run, 1.seconds) 

    println(result) // List("one", "two") 

請注意,你需要等待一個Future兩次,因爲EnumeratorIteratee控制的分別生產和消費值的速度。

一個更詳盡的例如用於Iteratee - 其中饋送Iteratee導致Enumerator產生值>Enumerator鏈:

// create an enumerator to which messages can be pushed 
    // using a channel 
    val (out, channel) = Concurrent.broadcast[String] 

    // create the input stream. When it receives an string, it 
    // will push the info into the channel 
    val in = 
    Iteratee.foreach[String] { s => 
     channel.push(s) 
    }.map(_ => channel.eofAndEnd()) 

    // Instead of using the complex `feed` method, we just create 
    // an enumerator that we can use to feed the input stream 
    val producer = Enumerator("one", "two").andThen(Enumerator.eof) 

    // Apply the input stream to the producer (feed the input stream) 
    val producedElementsFuture = producer.apply(in) 

    // Create a consumer for the output stream 
    val consumer = Iteratee.getChunks[String] 

    // Apply the consumer to the output stream (consume the output stream) 
    val consumedOutputStreamFuture = out.apply(consumer) 

    // Await the construction of the input stream chain 
    Await.result(producedElementsFuture, 1.second) 
    // Await the construction of the output stream chain 
    val consumedOutputStream = Await.result(consumedOutputStreamFuture, 1.second) 
    // Await consuming the output stream 
    val result = Await.result(consumedOutputStream.run, 1.second) 

    println(result) // List("one", "two")