Friday, February 22, 2008

A TCP/IP Echo Server in Scala

I thought I'd see what low level (for Java) network programming would be like in Scala and at the same time get used to using Scala's Actors for concurrency.

Starting with the basics, I've implemented an Echo server (which seems to be the "hello, world" of network programming). It's quite simple - wait for a connection, read a single line of text, send the text straight back and close the connection. Here's what I've come up with (I'm certain it could be made more concise, but then in Scala "there's always a more consise way to do it")


import java.net._
import java.io._

import scala.actors._
import scala.actors.Actor._

case class Echo(socket: Socket)

object Service extends Actor {

implicit def inputStreamWrapper(in: InputStream) =
new BufferedReader(new InputStreamReader(in))

implicit def outputStreamWrapper(out: OutputStream) =
new PrintWriter(new OutputStreamWriter(out))

def echo(in: BufferedReader, out: PrintWriter) {
val line = in.readLine()
out.println(line)
out.flush()
}

def act() {
loop {
receive {
case Echo(socket) =>
actor {
echo(socket.getInputStream(), socket.getOutputStream())
socket.close
}
}
}
}

}

object EchoServer {
Service.start

val serverSocket = new ServerSocket(12111)

def start() {
while(true) {
println("about to block")
val clientSocket = serverSocket.accept()
Service ! Echo(clientSocket)
println("back from actor")
}
}
}

EchoServer.start

2 comments:

Anonymous said...

i expect this is runnable WITH

object EchoServer extends Application

and WITHOUT

EchoServer.start

do you have a scala/java echoclient that would work with this server??

kdl said...

Anonymous1: telnet 127.0.0.1 12111
works just fine.

--
Thanks for the post!