Public domain Netstrings encoder/decoder class for Java

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

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);
        }
    }
    
}

Advertisement

2 Comments on “Public domain Netstrings encoder/decoder class for Java”

  1. Cool, but doesn’t appear to work well with multi-byte unicode chars. Netstrings should really use a byte[] to calculate the length.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 45 other followers