NioServer and NioClient
Origin
Hutool provides a simple encapsulation of NIO.
Usage
Server-side
NioServer server = new NioServer(8080);
server.setChannelHandler((sc)->{
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
try{
// Read data from the channel to the buffer
int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
// Flips this buffer. The limit is set to the current position and then
// the position is set to zero, indicating that data should be read from the beginning.
readBuffer.flip();
// Returns the number of elements between the current position and the limit.
// The length of bytes to be read.
byte[] bytes = new byte[readBuffer.remaining()];
// Read data from the buffer to the bytes array.
readBuffer.get(bytes);
String body = StrUtil.utf8Str(bytes);
Console.log("[{}]: {}", sc.getRemoteAddress(), body);
doWrite(sc, body);
} else if (readBytes < 0) {
IoUtil.close(sc);
}
} catch (IOException e){
throw new IORuntimeException(e);
}
});
server.listen();
public static void doWrite(SocketChannel channel, String response) throws IOException {
response = "Received message: " + response;
// Write buffer data to the channel and send it back to the client.
channel.write(BufferUtil.createUtf8(response));
}
Client-side
NioClient client = new NioClient("127.0.0.1", 8080);
client.setChannelHandler((sc)->{
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
// Read data from the channel to the buffer
int readBytes = sc.read(readBuffer);
if (readBytes > 0) {
// Flips this buffer. The limit is set to the current position and then
// the position is set to zero, indicating that data should be read from the beginning.
readBuffer.flip();
// Returns the number of elements between the current position and the limit.
// The length of bytes to be read.
byte[] bytes = new byte[readBuffer.remaining()];
// Read data from the buffer to the bytes array.
readBuffer.get(bytes);
String body = StrUtil.utf8Str(bytes);
Console.log("[{}]: {}", sc.getRemoteAddress(), body);
} else if (readBytes < 0) {
sc.close();
}
});
client.listen();
client.write(BufferUtil.createUtf8("Hello.\n"));
client.write(BufferUtil.createUtf8("Hello2."));
// Send data to the server from the console
Console.log("Please enter a message to send:");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String request = scanner.nextLine();
if (request != null && request.trim().length() > 0) {
client.write(BufferUtil.createUtf8(request));
}
}