Created
August 11, 2021 22:29
-
-
Save ChristopherDavenport/6cb0a96dcf5bcfa9021674ac6c938a85 to your computer and use it in GitHub Desktop.
Example of Asynchronous Socket Channel Pain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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