Backend Development 9 min read

Implementing WebSocket with Netty and Netty‑socketio: Server and Client Guide

This article explains the background, protocol basics, handshake process, and practical implementation of WebSocket using Netty and netty‑socketio on the server side and socket.io on the client side, providing full code examples and deployment tips for high‑concurrency real‑time applications.

Hujiang Technology
Hujiang Technology
Hujiang Technology
Implementing WebSocket with Netty and Netty‑socketio: Server and Client Guide

Background : To support CCtalk's web live video streaming and real‑time chat, short HTTP connections are insufficient; a long‑lived connection is required. Netty combined with WebSocket offers a scalable solution for handling massive concurrent connections.

Abstract : The article introduces the application of WebSocket within Netty, following two previous articles that covered the underlying principles and use cases.

What is WebSocket : Unlike traditional HTTP, which only allows client‑initiated requests, WebSocket provides full‑duplex communication over a single TCP connection, enabling both client and server to push messages at any time. The protocol became an international standard in 2011 and is supported by all modern browsers.

Handshake Phase : The client initiates the handshake with an HTTP Upgrade request containing headers such as Upgrade , Connection , Sec-WebSocket-Key , and optional Sec-WebSocket-Protocol . The server responds with a 101 Switching Protocols status, echoing Sec-WebSocket-Accept derived from the client's key, thereby upgrading the connection to WebSocket.

Long‑Connection Phase : After a successful handshake, the protocol switches to WebSocket frames, allowing bidirectional, low‑latency data exchange. The connection remains open until either side sends a close frame.

Server Implementation : The server uses the open‑source netty‑socketio library, which wraps Netty’s WebSocket handling. Add the Maven dependency:

<dependency>
  <groupId>com.corundumstudio.socketio</groupId>
  <artifactId>netty-socketio</artifactId>
  <version>1.7.12</version>
</dependency>

Key server code (simplified):

public static void main(String[] args) throws InterruptedException {
    final SocketIOServer server = new SocketIOServer(loadSocketIOConfig(doc));
    final SocketIONamespace ns = server.addNamespace("/echo");
    EchoConnectListener listener = new EchoConnectListener();
    EchoEventListener evtlistener = new EchoEventListener();
    ns.addConnectListener(listener);
    ns.addDisconnectListener(listener);
    ns.addEventListener(WebEventMessage.EVT_TAG, WebEventMessage.class, evtlistener);
    server.start();
    logger.info("============>WSServer started ... ok");
}

private static Configuration loadSocketIOConfig(Document doc) {
    Configuration config = new Configuration();
    config.setHostname(getNodeStr(doc, "host"));
    config.setPort(getNodeInt(doc, "port"));
    config.setBossThreads(getNodeInt(doc, "bossThreads"));
    config.setWorkerThreads(getNodeInt(doc, "workerThreads"));
    return config;
}

Event listener handling incoming messages and broadcasting responses:

public class EchoEventListener implements DataListener<WebEventMessage> {
    private static final Logger logger = LoggerFactory.getLogger(EchoEventListener.class);
    @Override
    public void onData(SocketIOClient client, WebEventMessage data, AckRequest ackSender) throws Exception {
        System.out.println("message:" + data.getMessage());
        WebEventMessage reply = new WebEventMessage();
        JSONObject obj = new JSONObject(data.getMessage());
        if (UserTokenMgr.getInstance().verify(obj.getInt("userid"), obj.getString("token"))) {
            reply.setMessage("login success");
        } else {
            reply.setMessage("login failed");
        }
        client.getNamespace().getBroadcastOperations().sendEvent(WebEventMessage.EVT_TAG, reply);
    }
}

Client Implementation : The client uses the JavaScript socket.io library to connect to the server namespace ws://example.com:8080/echo . Sample code for connection, event handling, and sending messages:

var socket = io.connect('http://127.0.0.1:8080/echo');
socket.on('connect', function() {
    output('<span class="connect-msg">Client has connected to the server!</span>');
});
socket.on('message', function(data) {
    output('<span class="username-msg"> echo' + ':</span> ' + data.message);
});
socket.on('disconnect', function() {
    output('<span class="disconnect-msg">The client has disconnected!</span>');
});
var message = JSON.stringify(jsonmsg);
var cmd = 1;
var jsonObject = {'@class':'WebEventMessage', cmd:cmd, message:message};
socket.emit('message', jsonObject, function(arg1, arg2) {});

Conclusion : Using Netty‑based WebSocket delivers high performance and greatly improves the user experience of live streaming and chat features. CCtalk’s web live platform and other products already employ this architecture, and the article invites readers to experiment and share improvements.

BackendJavanettyWebSocketreal-time communicationSocketIO
Hujiang Technology
Written by

Hujiang Technology

We focus on the real-world challenges developers face, delivering authentic, practical content and a direct platform for technical networking among developers.

0 followers
Reader feedback

How this landed with the community

login 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.