Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
118 lines (89 sloc) 2.6 KB
object Client {
def runs(x: Int) = {
val runners = (1 to x).map(i => runner(i))
val threads = runners.map(new Thread(_))
threads.foreach(_.start())
threads.foreach(_.join())
val successes = runners.filter(_.successful).size
val failures = runners.filterNot(_.successful).size
println("successes: " + successes + ", failures: " + failures)
}
private def runner(x: Int) = new Runnable {
var successful = false
def go() {
val socket = new java.net.Socket(java.net.InetAddress.getLocalHost, 5554)
val oos = new java.io.ObjectOutputStream(socket.getOutputStream())
oos.writeObject("hello")
val ois = new java.io.ObjectInputStream(socket.getInputStream())
println("client " + x + "> " + ois.readObject())
ois.close()
oos.close()
socket.close()
}
def run() = try {
go()
successful = true
} catch {
case e: java.net.SocketException => println("client " + x + "> rejected")
}
}
}
object Executor {
def spawn(f: => Unit) = {
new Thread(
new Runnable {
def run() {
f
}
}
).start()
}
}
object SyncServer {
def run() = Executor.spawn{
while (true) {
val server = new java.net.ServerSocket(5554, 1)
val socket = server.accept()
server.close()
val ois = new java.io.ObjectInputStream(socket.getInputStream())
val request = ois.readObject().toString
Thread.sleep(250)
val response = "response(" + request + ")"
val oos = new java.io.ObjectOutputStream(socket.getOutputStream())
oos.writeObject(response)
oos.close()
ois.close()
socket.close()
}
}
}
object AsyncServer {
import util.continuations._
private var queue: List[Unit => Unit] = Nil
private val handler = Executor.spawn {
while (true) queue match {
case Nil => Thread.sleep(10)
case head :: tail =>
queue = tail
head()
}
}
def run() = Executor.spawn {
while (true) reset {
val server = new java.net.ServerSocket(5554, 1)
val socket = server.accept()
server.close()
suspend()
val ois = new java.io.ObjectInputStream(socket.getInputStream())
val request = ois.readObject().toString
Thread.sleep(250)
val response = "response(" + request + ")"
val oos = new java.io.ObjectOutputStream(socket.getOutputStream())
oos.writeObject(response)
oos.close()
ois.close()
socket.close()
}
}
def suspend() = shift { k: (Unit => Unit) => queue = k :: queue }
}
Something went wrong with that request. Please try again.