Chapter 7: Understanding the MessageProcessor Mechanism in smart‑socket

This article explains the core MessageProcessor interface of the smart‑socket framework, detailing its process and stateEvent methods, the associated StateMachineEnum events, example implementations for echo and business logic servers, and recommended best‑practice guidelines for robust message handling.

Three Knives
Three Knives
Three Knives
Chapter 7: Understanding the MessageProcessor Mechanism in smart‑socket

MessageProcessor Interface

The MessageProcessor<T> interface is the entry point for business‑logic handling in the smart‑socket framework.

Interface definition

public interface MessageProcessor<T> {
    /**
     * Process the received message.
     * @param session communication session
     * @param msg the business message to handle
     */
    void process(AioSession session, T msg);

    /**
     * State‑machine event triggered by the framework.
     * @param session the AioSession that triggered the event
     * @param stateMachineEnum the state enum
     * @param throwable optional exception
     */
    default void stateEvent(AioSession session, StateMachineEnum stateMachineEnum, Throwable throwable) {
        if (stateMachineEnum == StateMachineEnum.DECODE_EXCEPTION ||
            stateMachineEnum == StateMachineEnum.PROCESS_EXCEPTION) {
            throwable.printStackTrace();
        }
    }
}

Core methods

process : handles a decoded business message.

stateEvent : handles state‑machine events; the default implementation prints stack traces for decode or processing exceptions.

process method details

Parameters:

session : the current communication session, used to obtain session information and to send data.

msg : the already‑decoded business message; its concrete type depends on the protocol.

Example implementation of process

MessageProcessor<String> serverProcessor = (session, msg) -> {
    String resp = "hi," + msg;
    System.out.println("receive data from client: " + msg + " ,rsp:" + resp);
    byte[] bytes = resp.getBytes();
    session.writeBuffer().writeInt(bytes.length);
    session.writeBuffer().write(bytes);
    session.writeBuffer().flush();
};

stateEvent method details

Handles internal state‑machine events such as session creation, closure, and exceptions.

StateMachineEnum values

NEW_SESSION, REJECT_ACCEPT, ACCEPT_EXCEPTION, DECODE_EXCEPTION,
INPUT_EXCEPTION, OUTPUT_EXCEPTION, INPUT_SHUTDOWN, PROCESS_EXCEPTION,
INTERNAL_EXCEPTION, SESSION_CLOSING, SESSION_CLOSED

Custom stateEvent handling example

MessageProcessor<String> processor = new MessageProcessor<String>() {
    @Override
    public void process(AioSession session, String msg) {
        System.out.println("Received: " + msg);
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum state, Throwable throwable) {
        switch (state) {
            case NEW_SESSION:
                System.out.println("New session created: " + session.getSessionID());
                break;
            case SESSION_CLOSED:
                System.out.println("Session closed: " + session.getSessionID());
                break;
            case PROCESS_EXCEPTION:
                System.err.println("Processing exception occurred:");
                throwable.printStackTrace();
                break;
            default:
                MessageProcessor.super.stateEvent(session, state, throwable);
        }
    }
};

Practical application scenarios

Scenario 1 – Simple Echo server

public class EchoMessageProcessor implements MessageProcessor<String> {
    @Override
    public void process(AioSession session, String msg) {
        session.writeBuffer().write(msg.getBytes());
        session.writeBuffer().flush();
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum state, Throwable throwable) {
        if (state == StateMachineEnum.SESSION_CLOSED) {
            System.out.println("Client disconnected: " + session.getSessionID());
        }
    }
}

Scenario 2 – Business logic processor

public class BusinessMessageProcessor implements MessageProcessor<String> {
    @Override
    public void process(AioSession session, String msg) {
        if (msg.startsWith("login:")) {
            String username = msg.substring(6);
            session.setAttachment(username);
            System.out.println("User login: " + username);
        } else if (msg.startsWith("chat:")) {
            String chatMsg = msg.substring(5);
            String username = session.getAttachment();
            System.out.println(username + " says: " + chatMsg);
        } else {
            System.out.println("Unknown command: " + msg);
        }
    }

    @Override
    public void stateEvent(AioSession session, StateMachineEnum state, Throwable throwable) {
        switch (state) {
            case NEW_SESSION:
                System.out.println("New session created: " + session.getSessionID());
                break;
            case SESSION_CLOSED:
                System.out.println("Session closed: " + session.getSessionID());
                break;
            default:
                MessageProcessor.super.stateEvent(session, state, throwable);
        }
    }
}

Best‑practice recommendations

Handle business‑logic exceptions inside process to avoid destabilizing the framework.

Offload long‑running tasks to a thread pool to prevent blocking I/O threads.

Release session‑related resources promptly; perform cleanup when a session closes.

Leverage stateEvent to observe session state changes and collect runtime metrics.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaState Machineasynchronousnetworkingsmart-socketMessageProcessor
Three Knives
Written by

Three Knives

Every line of code you contribute to open source could help make the future better.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.