Skip to content

Instantly share code, notes, and snippets.

@ChristopherDavenport
Created August 11, 2021 22:29
Show Gist options
  • Save ChristopherDavenport/6cb0a96dcf5bcfa9021674ac6c938a85 to your computer and use it in GitHub Desktop.
Save ChristopherDavenport/6cb0a96dcf5bcfa9021674ac6c938a85 to your computer and use it in GitHub Desktop.
Example of Asynchronous Socket Channel Pain
import cats.effect._
import java.nio.channels.AsynchronousSocketChannel
import java.nio.ByteBuffer
import java.net.InetSocketAddress
import java.nio.channels.{AsynchronousSocketChannel, CompletionHandler}
import java.nio.{Buffer, ByteBuffer}
object Main extends IOApp {
def run(args: List[String]): IO[ExitCode] = {
IO{
val client = AsynchronousSocketChannel.open()
val hostAddress = new InetSocketAddress("localhost", 8080)
val future = client.connect(hostAddress)
future.get()
println(client.getLocalAddress())
println("Kill Server Now")
System.console().readLine()
// Thread.sleep(10000)
val msg1 = "Hello, world".getBytes()
val buf1 = ByteBuffer.wrap(msg1)
val write1 = client.write(
buf1,
null,
new IntCallbackHandler(cb => println(cb))
)
}.as(ExitCode.Success)
}
private final class IntCallbackHandler[A](cb: Either[Throwable, Int] => Unit)
extends CompletionHandler[Integer, AnyRef] {
def completed(result: Integer, attachment: AnyRef): Unit =
cb(Right(result))
def failed(err: Throwable, attachment: AnyRef): Unit =
cb(Left(err))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment