Sunday, July 14, 2013

Group Connections with WebSocket


This article describe how to group connections of WebSocket with server side grouping information.

Environment: Tomcat 7.0.42


Simple WebSocket Test with Tomcat


View demo on line



Create and trigger WebSocket connection with specified group.

<%@ page language="java"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- EL is required -->
<%@ page isELIgnored ="false" %>
        <meta http-equiv="Content-Type" 
            content="text/html; charset=UTF-8"/>
        <title>practice one</title>
        <script type="text/javascript">
            var TestWebSocket = {
                socket: null,
                group: null,
                connect: (function() {
                    // store the specified group
           = '${GROUP}';
                    // create WebSocket with the specified group
                    var loc = window.location,
                        host = ('ws://' + + loc.pathname).replace('index.jsp', '') + + '.wsreq';
                    if ('WebSocket' in window) {
                        TestWebSocket.socket = new WebSocket(host);
                    } else if ('MozWebSocket' in window) {
                        TestWebSocket.socket = new MozWebSocket(host);
                    } else {
                        alert('Error: WebSocket is not supported by this browser.');
                    // process message from server
                    TestWebSocket.socket.onmessage = function (message) {
                        document.getElementById('content').innerHTML =;
                // send specified group to server
                trigger: (function() {

        Group: ${GROUP}
        <div id="content"></div>
        <button id="btn" onclick="TestWebSocket.trigger();">trigger</button>

Used to specify group, update it to client side.

package test;

import java.util.Random;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebFilter(filterName="TestFilter", urlPatterns={"/index.jsp"})
public class TestFilter implements Filter {
    private static final String[] _groups = {"GroupOne", "GroupTwo", "GroupThree"};
    public void init(FilterConfig filterConfig) throws ServletException {

    public void doFilter(ServletRequest request, ServletResponse response,
             FilterChain chain) throws IOException, ServletException {
        Random r = new Random();
        // put the value "GroupOne"/"GroupTwo"/"GroupThree" with
        // name "GROUP" into request scope
        ((HttpServletRequest)request).setAttribute("GROUP", _groups[r.nextInt(3)]);
        chain.doFilter(request, response);

    public void destroy() {}

Create server side connections with specified group.

package test;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

 * Tested with Tomcat 7.0.42
 * @author benbai123
public class TestWebSocketServlet extends WebSocketServlet {

    private static final long serialVersionUID = -7663708549630020769L;

    // for message that will be sent to client
    private final AtomicInteger _cntForGroupOne = new AtomicInteger(0);
    private final AtomicInteger _cntForGroupTwo = new AtomicInteger(0);
    private final AtomicInteger _cntForGroupThree = new AtomicInteger(0);
    // hold each connection in this Set
    private final Set<TestMessageInbound> connections =
        new CopyOnWriteArraySet<TestMessageInbound>();
     * For create connection only, each connection will
     * handle it self as needed
    protected StreamInbound createWebSocketInbound(String subProtocol,
            HttpServletRequest request) {
        String uri = request.getRequestURI();
        String group = uri.substring(uri.lastIndexOf("/")+1, uri.length()).replace(".wsreq", "");

        // Create connection with specified group
        return new TestMessageInbound(group);
    private final class TestMessageInbound extends MessageInbound {
        private String _group;
        public TestMessageInbound (String group) {
            _group = group;
        // add self instance into connections Set while opened
        protected void onOpen(WsOutbound outbound) {
        // remove self instance from connections Set whild closed
        protected void onClose(int status) {
        // ignore binary message since we just want to process text messages
        protected void onBinaryMessage(ByteBuffer message) throws IOException {
            // ignore
        // send a message to each connection in connections Set
        // while receive a text message (specific group here)
        protected void onTextMessage(CharBuffer message) throws IOException {
        public String getGroup () {
            return _group;
    // send message to specific group
    public void send (String group) {
        String msg = "Current count for " + group + ": " + getCounterByGroup(group);;
        for (TestMessageInbound connection : connections) {
            try {
                if (group.equals(connection.getGroup())) {
            } catch (IOException ignore) {
                /* ignore */
    // get message for specific group
    private int getCounterByGroup (String group) {
        return "GroupOne".equals(group)? _cntForGroupOne.incrementAndGet() :
            "GroupTwo".equals(group)? _cntForGroupTwo.incrementAndGet() : _cntForGroupThree.incrementAndGet();


For servlet mapping

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""


Full project at github

Demo Flash

No comments:

Post a Comment