Build a Real‑Time Message Push Service with Spring Boot, Netty and WebSocket
This article walks through creating a Netty‑based WebSocket server integrated with Spring Boot, covering server bootstrap, global channel management, pipeline configuration, a custom handler for client messages, and a push‑message service that can target individual users or broadcast to all connections, complete with code samples and testing steps.
Spring Boot developers can leverage Netty’s efficient NIO abstraction to build a WebSocket server that pushes messages to connected clients. The guide starts by creating a @Component class NettyServer that reads the port from ${webSocket.netty.port:8888}, initializes bossGroup and workGroup as NioEventLoopGroup instances, and configures a ServerBootstrap with NioServerSocketChannel. After binding to the port, the server logs the listening address and waits for the channel to close, ensuring graceful shutdown of the event loops.
Netty Configuration
A singleton NettyConfig class holds a volatile ChannelGroup for managing all active channels and a ConcurrentHashMap<String, Channel> that maps user IDs to their channels. Thread‑safe lazy initialization uses double‑checked locking with two separate lock objects.
Pipeline Configuration
The ProjectInitializer extends ChannelInitializer<SocketChannel> and sets up the pipeline with the following handlers: HttpServerCodec – HTTP encoder/decoder. ObjectEncoder – serializes objects. ChunkedWriteHandler – supports writing large data streams. HttpObjectAggregator(8192) – aggregates HTTP messages.
WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL, true, 65536 * 10)– handles the WebSocket handshake and frames. webSocketHandler – custom business logic handler.
Custom WebSocket Handler
The WebSocketHandler (annotated with @Component and @ChannelHandler.Sharable) extends SimpleChannelInboundHandler<TextWebSocketFrame>. It logs new connections, adds channels to the global group, parses incoming JSON messages to extract a uid, stores the mapping in NettyConfig.getChannelMap(), attaches the user ID as a channel attribute, and echoes a confirmation back to the client. It also handles channel removal and exceptions by cleaning up the group and attribute map.
Push Message Service
An interface PushMsgService defines two methods: pushMsgToOne(String userId, String msg) and pushMsgToAll(String msg). The implementation PushMsgServiceImpl retrieves the target channel from NettyConfig.getChannel(userId), throws a RuntimeException if the user is offline, and writes a TextWebSocketFrame to the channel. Broadcasting uses the global ChannelGroup to write the frame to all connected clients.
Testing the Server
After starting the Spring Boot application, the Netty server listens on the configured port. Clients can connect via the WebSocket endpoint (e.g., ws://host:port/webSocket), send JSON messages containing a uid, and receive server acknowledgments. The provided screenshots illustrate connecting, sending messages, and observing the push notifications on the front end. The final step calls the push‑message service to broadcast messages, confirming that the end‑to‑end flow works as expected.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IoT Full-Stack Technology
Dedicated to sharing IoT cloud services, embedded systems, and mobile client technology, with no spam ads.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
