Introduction
This article describe how to group connections of WebSocket with server side grouping information.
Environment: Tomcat 7.0.42
Pre-request
Simple WebSocket Test with Tomcat
http://ben-bai.blogspot.tw/2013/07/simple-websocket-test-with-tomcat.html
Result
View demo on line
http://screencast.com/t/uc9VPj2k
Program
index.jsp
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" %>
<html>
<head>
<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
TestWebSocket.group = '${GROUP}';
// create WebSocket with the specified group
var loc = window.location,
host = ('ws://' + loc.host + loc.pathname).replace('index.jsp', '') + TestWebSocket.group + '.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.');
return;
}
// process message from server
TestWebSocket.socket.onmessage = function (message) {
document.getElementById('content').innerHTML = message.data;
};
}),
// send specified group to server
trigger: (function() {
TestWebSocket.socket.send(TestWebSocket.group);
})
};
TestWebSocket.connect();
</script>
</head>
<body>
Group: ${GROUP}
<div id="content"></div>
<button id="btn" onclick="TestWebSocket.trigger();">trigger</button>
</body>
</html>
TestFilter.java
Used to specify group, update it to client side.
package test;
import java.io.IOException;
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"};
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
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);
}
@Override
public void destroy() {}
}
TestWebSocketServlet.java
Create server side connections with specified group.
package test;
import java.io.IOException;
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
*/
@Override
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
@Override
protected void onOpen(WsOutbound outbound) {
connections.add(this);
}
// remove self instance from connections Set whild closed
@Override
protected void onClose(int status) {
connections.remove(this);
}
// ignore binary message since we just want to process text messages
@Override
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)
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
send(message.toString());
}
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())) {
connection.getWsOutbound().writeTextMessage(CharBuffer.wrap(msg));
}
} 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();
}
}
web.xml
For servlet mapping
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>TomcatWebSocketTest</display-name>
<servlet>
<servlet-name>testWebSocketServlet</servlet-name>
<servlet-class>test.TestWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testWebSocketServlet</servlet-name>
<url-pattern>*.wsreq</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Download
Full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/WebServer/WebSocket/GroupConnectionsWithWebSocket
Demo Flash
https://github.com/benbai123/JSP_Servlet_Practice/blob/master/demo_src/Server/Tomcat/GroupConnectionsWithWebSocket.swf
No comments:
Post a Comment