Created
April 20, 2018 12:45
-
-
Save sidharthkuruvila/90533d91d805ef28653dbc764c3530c1 to your computer and use it in GitHub Desktop.
Simple client server application using AsynchronousSocketChannel
This file contains 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
package server | |
import java.io.ObjectInputStream | |
import java.net.SocketAddress | |
import java.nio.ByteBuffer | |
import java.nio.channels.AsynchronousServerSocketChannel | |
import java.nio.channels.AsynchronousSocketChannel | |
import java.nio.channels.CompletionHandler | |
import java.nio.charset.Charset | |
import java.util.concurrent.locks.Lock | |
import java.util.concurrent.locks.ReadWriteLock | |
import java.util.concurrent.locks.ReentrantLock | |
class ServerApplication { | |
companion object { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val lock = ReadWriteLock() | |
lock.newCondition(). | |
val ois: ObjectInputStream | |
AsynchronousServerSocketChannel.open().bind(null).use { server -> | |
server.accept(null, object : CompletionHandler<AsynchronousSocketChannel, Nothing?> { | |
override fun failed(exc: Throwable, attachment: Nothing?) { | |
log("Failed to accept connection") | |
exc.printStackTrace() | |
log("We done") | |
} | |
override fun completed(channel: AsynchronousSocketChannel, attachment: Nothing?) { | |
server.accept(null, this) | |
val bb = ByteBuffer.allocate(1000) | |
val nFuture = channel.read(bb) | |
nFuture.get() | |
bb.flip() | |
log(Charset.defaultCharset().decode(bb).toString()) | |
} | |
}) | |
(1..10).forEach { | |
clientCall(server.localAddress, it) | |
} | |
} | |
Thread.sleep(1000) | |
} | |
private fun clientCall(socketAddress: SocketAddress, n: Int) { | |
AsynchronousSocketChannel.open().use { chan -> | |
chan.connect(socketAddress).get() | |
val bb = ByteBuffer.wrap("Hello %d".format(n).toByteArray()) | |
val f = chan.write(bb) | |
f.get() | |
} | |
} | |
fun log(msg: String) { | |
println("Thread %s: %s".format(Thread.currentThread().name, msg)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment