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.
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) { ... }
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
.
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()
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)