Monday, January 21, 2008

A Socket Client for Groovy

Groovy Rocks!! I needed a simple client that would write data to a socket to test this application I was working on so I wrote it in Java since I had done that before. My code looked like the following:


public static void main(String[] args) throws Exception {
String data = "test data";
InputStream is = new ByteArrayInputStream(data.getBytes());

Socket socket = new Socket("localhost", 8282);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader bw = new BufferedReader(new InputStreamReader(
socket.getInputStream()));

BufferedReader br = new BufferedReader(new InputStreamReader(is));
String userInput;

if ((userInput = br.readLine()) != null) {
System.out.println("yeb");
pw.println(userInput);
pw.close();
bw.close();
br.close();
socket.close();
System.exit(200);
}
}


After I got done, I was curious how I could do this same sort of thing in Groovy. So, I spun up the Groovy Shell and away I went.....


s = new Socket("localhost", 8283)
s << "Groovy Rocks"
s.close()


... I type go in my groovy shell and I'm done. Seriously, 3 lines of code and a quick shell to test it out. Groovy is awesome.