Skip to content

Instantly share code, notes, and snippets.

@pfn
Created December 22, 2013 23:20
Show Gist options
  • Select an option

  • Save pfn/8089619 to your computer and use it in GitHub Desktop.

Select an option

Save pfn/8089619 to your computer and use it in GitHub Desktop.
withSocketAsync
def withSocketAsync[A](s: => Socket)
(f: (Socket,java.io.Reader,java.io.Writer) => A)
: Future[A] = {
val promise = Promise[A]()
val sock = s
async {
try {
val in = new InputStreamReader(sock.getInputStream, "utf-8")
val out = new OutputStreamWriter(sock.getOutputStream, "utf-8")
try {
promise.success(f(sock, in, out))
} finally {
out.close()
in.close()
sock.close()
}
} catch {
case t: Throwable => e("failed", t); promise.failure(t)
}
}
promise.future
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment