Skip to content

Instantly share code, notes, and snippets.

@maheshkhanwalkar
Last active December 12, 2019 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maheshkhanwalkar/534c7e4f6b0cd1ceb5df to your computer and use it in GitHub Desktop.
Save maheshkhanwalkar/534c7e4f6b0cd1ceb5df to your computer and use it in GitHub Desktop.
Using the SocketUtil Helper Class

Using the SocketUtil Helper Class

In NioFlex, the SocketUtil class contains a set of methods that make interfacing with raw Java NIO a lot easier.

It is mandatory that you use this API to perform NIO operations because of how the server is designed, but don't worry, the API is extremely easy to learn.

The Constructor

public SocketUtil(SocketChannel channel) { ... }

In the handleRead() method, you are passed a SocketUtil class as one of the parameters, so, you don't need to construct another one.

@Override
public void handleRead(SocketChannel client, SelectionKey key, SocketUtil util) { ... }

ByteBuffers

The very base of Java NIO is a ByteBuffer which is used for all NIO read/write operations. However, they can be tedious to work with - which is why the SocketUtil class exists.

However, the SocketUtil class still provides methods to read data into and write data from ByteBuffers.

To read data into a ByteBuffer use:

public ByteBuffer readBuffer(int len)

So, if you want to read 1024 bytes (into a ByteBuffer) from a SocketChannel, you would:

ByteBuffer data = util.readBuffer(1024);

where, util is a instance of SocketUtil.

Reading Primitive Types

The SocketUtil API has many methods to read primitive Java types from SocketChannels:

public byte[] readBytes(int len)
public String readString(int len)

public String readString(int len, Charset charset)
public int readInt()

public short readShort()
public long readLong()

Writing Primitive Types

The SocketUtil API also has many methods to write primitive Java types to SocketChannels:

public void writeBuffer(ByteBuffer buf)  //not a primitive, but also included
public void writeBytes(byte[] bytes)

public void writeString(String str)
public void writeString(String str, Charset charset)

public void writeInt(int num)

public void writeShort(short num)
public void writeLong(long num)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment