public class TailorWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = -7289719281366784056L;
public static String newLine = System.getProperty("line.separator");
private final Set<TailorSocket> _members = new CopyOnWriteArraySet<TailorSocket>();
private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
public void init() throws ServletException {
super.init();
executor.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("Running Server Message Sending");
for(TailorSocket member : _members){
System.out.println("Trying to send to Member!");
if(member.isOpen()){
System.out.println("Sending!");
try {
member.sendMessage("from server : happy and happiness! "+new Date()+newLine);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}, 2, 2, TimeUnit.SECONDS);
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
getServletContext().getNamedDispatcher("default").forward(request,
response);
}
public WebSocket doWebSocketConnect(HttpServletRequest request,
String protocol) {
return new TailorSocket();
}
class TailorSocket implements WebSocket.OnTextMessage {
private Connection _connection;
public void onClose(int closeCode, String message) {
_members.remove(this);
}
public void sendMessage(String data) throws IOException {
_connection.sendMessage(data);
}
public void onMessage(String data) {
System.out.println("Received: "+data);
}
public boolean isOpen() {
return _connection.isOpen();
}
public void onOpen(Connection connection) {
_members.add(this);
_connection = connection;
try {
connection.sendMessage("onOpen:Server received Web Socket upgrade and added it to Receiver List.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
test.html
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset = "utf-8"/>
<title>Chat by Web Sockets</title>
<script type='text/javascript'>
if (!window.WebSocket)
alert("window.WebSocket unsuport!");
function $() {
return document.getElementById(arguments[0]);
}
function $F() {
return document.getElementById(arguments[0]).value;
}
function getKeyCode(ev) {
if (window.event)
return window.event.keyCode;
return ev.keyCode;
}
var server = {
connect : function() {
var location ="ws://localhost:8888/servlet/a";
this._ws =new WebSocket(location);
this._ws.onopen =this._onopen;
this._ws.onmessage =this._onmessage;
this._ws.onclose =this._onclose;
},
_onopen : function() {
server._send('send to server : websockets are open for communications!');
},
_send : function(message) {
if (this._ws)
this._ws.send(message);
},
send : function(text) {
if (text !=null&& text.length >0)
server._send(text);
},
_onmessage : function(m) {
if (m.data) {
var messageBox = $('messageBox');
var spanText = document.createElement('span');
spanText.className ='text';
spanText.innerHTML = m.data;
var lineBreak = document.createElement('br');
messageBox.appendChild(spanText);
messageBox.appendChild(lineBreak);
messageBox.scrollTop = messageBox.scrollHeight
- messageBox.clientHeight;
}
},
_onclose : function(m) {
this._ws =null;
}
};
</script>
<style type='text/css'>
div {
border: 0px solid black;
}
div#messageBox {
clear: both;
width: 40em;
height: 20ex;
overflow: auto;
background-color: #f0f0f0;
padding: 4px;
border: 1px solid black;
}
div#input {
clear: both;
width: 40em;
padding: 4px;
background-color: #e0e0e0;
border: 1px solid black;
border-top: 0px
}
div.hidden {
display: none;
}
span.alert {
font-style: italic;
}
</style>
</head>
<body>
<div id='messageBox'></div>
<div id='input'>
<div>
<input id='connect' class='button' type='submit' name='Connect'
value='Connect' />
</div>
</div>
<script type='text/javascript'>
$('connect').onclick =function(event) {
server.connect();
returnfalse;
};
</script>
<p>
JAVA Jetty for WebSocket
</p>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<!-- ==================================================================
Configure and deploy the test web application in $(jetty.home)/webapps/test
Note. If this file did not exist or used a context path other that /test
then the default configuration of jetty.xml would discover the test
webapplication with a WebAppDeployer. By specifying a context in this
directory, additional configuration may be specified and hot deployments
detected.
===================================================================== -->
<Configure class="org.eclipse.jetty.webapp.WebAppContext">