Archive for January, 2010

Public domain Netstrings encoder/decoder class for Java

January 17, 2010

According to D. J. Bernstein, who created the simplistic protocol in 1997, a netstring “is a self-delimiting encoding of a string. Netstrings are very easy to generate and to parse. Any string may be encoded as a netstring; there are no restrictions on length or on allowed bytes. Another virtue of a netstring is that it declares the string size up front. Thus an application can check in advance whether it has enough space to store the entire string.” (More information on Wikipedia.)

Netstrings are great for when you are writing a network program that needs a simple protocol to communicate data between client and server (or client/client). Because of this, it has been my choice for small pieces of software that I write. I was sad to find, however, that Java does not have built-in netstrings capabilities — so I decided to write my own. The source code to my minimalistic yet functional implementation is below.

// Public domain Netstrings encoder/decoder class for Java
// Version 1.0 - Written by Brian Nez

public class Netstrings {

    public static String encode(String message) {
        int length = message.length();
        message = new String(length + ":" + message + ",");
        return message;
    }

    public static String decode(String original) {
        String result = original.split(":", 2)[1];
        if(result.length()-1 != Integer.parseInt(original.split(":")[0])) {
            System.out.println("Netstring integrity error: Expected length " + original.split(":")[0] + " but got length " + (result.length()-1) );
            return null;
        } else {
        	return result.substring(0, result.length()-1);
        }
    }

}