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

Tuesday, February 12, 2008

New Toy - Asus Eee PC

Sorry for the lull in my Scala vs Groovy posts - I bought a new toy a couple weeks back and it's been sucking up my free time. I've got three posts mostly finished and they should be out soon. The funny thing is that I bought the thing to become more productive.

As for the device itself - it's fantastic. I ended up buying the 2G Surf model (512 meg of RAM, 2 gig SSD), basically because it was available and I wanted one right then and there (unsurprisingly the 4Gs were few and far between). While I'd recommend the 4G version to anyone buying one (as there's at least a chance that you can upgrade the memory in the 4G, it's got a better battery and isn't as underclocked), the 2G is fine for what I wanted (as I was going to install Xubuntu to a SDHC card no matter what model I was going to get).

Xubuntu installed fine (though a very small amount of extra work was needed to get WiFi and sound working), Java's running fine (though I've yet to test Scala and Groovy), mplayer's runs (though I think it'll run better with the underclocking switched off, yet another item on the to do list). Firefox runs and Google Reader's offline mode makes for a great way to pass the time on the tube to work.