Module id.ICE

ICE is a Java module which helps you to build non-blocking I/O message based servers.

With ICE you can implement servers for existing protocols (like HTTP) or your own.

ICE supports following types of interaction:

  • request/response -- this is when client sends a request message and server process it and returns a message back with response
  • request/multiple responses -- same as before except in this case server may returns multiple messages back to the client with multiple responses

By default after ICE sends the message back to client it keeps the connection open waiting for another request. But you can easily change this and ask ICE to close it right after response is sent.

ICE non-blocking I/O is based on Java Async Channels rather than separate native libraries. This makes ICE really crossplatform and small.

ICE has no dependencies on obsolete sun.misc.Unsafe and others so it makes it easy to include into custom Java runtime images.

Samples

Here are the samples for different basic server implementations.

Echo service

Echo service receives a string from the client and sends it back.

Service implementation:


public class EchoService implements MessageService {
    @Override
    public CompletableFuture<MessageResponse> process(MessageRequest request) {
        // obtaining and printing data from the request
        var inputData = request.getMessage().get();
        System.out.println(new String(inputData.array()));
        
        // generating response with same data and sending back
        byte[] outputData = new byte[inputData.capacity()];
        inputData.get(outputData, 0, inputData.capacity());
        return CompletableFuture.completedFuture(new MessageResponse(ByteBuffer.wrap(outputData)));
    }
}
 

Usage:


try (var server = new MessageServer(new EchoService(), new NewLineMessageScanner())) {
    server
        .withNumberOfThreads(1)
        .withPort(10007);
    server.run();
    
    // keep running until user press Enter
    System.in.read();
} catch (Exception e) {
    e.printStackTrace();
}
 

Now you can connect to local port 10007 and type any text which will be repeated to you back once you press Enter.

See Also:
Download ICE, Github