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.

7 comments:

hombi's blog said...

cool, but where is the socket reading implementation?

Chad Gallemore said...

You should be able to run the following from the command line:

groovy -l 8282 -e "System.err.println line"

partyk1d24 said...

Is it possible for you to add an example of a simple Client Server that does the same thing? For example if I have a server program waiting for responses from a client on a server.

Basically how would I listen to the input buffer as opposed to just writing to the socket?

partyk1d24 said...

Can you give an example of how to create an actual client that is consuuming the socket comunication (printing out the read) not just a command line?

Chad Gallemore said...

Check out this, it should get you going on the right track.

Chris said...

Its Awesome!
I am trying to figure out this since long back. But no luck.
It helps me a lot in configuring a remote jboss server with jconsole.

Much Appreciated!!

Regards,
Chris.

Anonymous said...

Nice, I was looking at how to quick do that in groovy and your post just got me what I need.