Skip to content

Instantly share code, notes, and snippets.

@jsuereth
Created May 14, 2011 02:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsuereth/971618 to your computer and use it in GitHub Desktop.
Save jsuereth/971618 to your computer and use it in GitHub Desktop.
IterateeNonBlockingEchoServer
package scalaz.example.nio
import scalaz._
import concurrent.Promise
import effects.IO
import nio.sockets._
import nio.Channels._
import Scalaz._
import iteratees._
import java.nio.channels.SocketChannel
import java.nio.channels.ByteChannel
import java.nio.ByteBuffer
object ExampleSocketServer {
def run(implicit s: concurrent.Strategy) {
val server = serverSocketChannel(8080)
val firstConnection : IO[Promise[SocketChannel]] =
server.map(s => FlattenI(s(head[Promise, SocketChannel]))).map(_.run.map(_.get))
val echo : IO[Iteratee[ByteBuffer, Promise, Unit]] = firstConnection flatMap { futureSocket =>
val consumer = writeToChannel[Promise](futureSocket.map(_.asInstanceOf[ByteChannel]))
val reader = futureSocket map (i => readSocketChannel(i))
reader.get map (e => FlattenI(e(consumer)))
}
val runner : IO[Unit] = echo.map(_.run)
runner.unsafePerformIO
}
}
@jsuereth
Copy link
Author

Simple echo server in my scalaz nio branch. Comments welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment