Skip to content

Instantly share code, notes, and snippets.

@manzke
Created June 12, 2011 21:04
Show Gist options
  • Save manzke/1021982 to your computer and use it in GitHub Desktop.
Save manzke/1021982 to your computer and use it in GitHub Desktop.
Jetty 7+8 Web Socket Example
package de.devsurf.html.tail;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
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();
@Override
public void init() throws ServletException {
super.init();
executor.scheduleAtFixedRate(new Runnable() {
@Override
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("Sending a Message to you Guys! "+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;
@Override
public void onClose(int closeCode, String message) {
_members.remove(this);
}
public void sendMessage(String data) throws IOException {
_connection.sendMessage(data);
}
@Override
public void onMessage(String data) {
System.out.println("Received: "+data);
}
public boolean isOpen() {
return _connection.isOpen();
}
@Override
public void onOpen(Connection connection) {
_members.add(this);
_connection = connection;
try {
connection.sendMessage("Server received Web Socket upgrade and added it to Receiver List.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<html>
<head>
<title>Tail-based by Web Sockets</title>
<script type='text/javascript'>
if (!window.WebSocket)
alert("WebSocket not supported by this browser");
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 = document.location.toString().replace('http://',
'ws://').replace('https://', 'wss://').replace('test.html','servlet/WebSocket');
alert(location);
this._ws = new WebSocket(location);
this._ws.onopen = this._onopen;
this._ws.onmessage = this._onmessage;
this._ws.onclose = this._onclose;
},
_onopen : function() {
server._send('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();
return false;
};
</script>
<p>
This is a demonstration of the Jetty websocket server.
</p>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<display-name>tailor</display-name>
<servlet>
<servlet-name>WebSocket</servlet-name>
<servlet-class>de.devsurf.html.tail.TailorWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WebSocket</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>test.html</welcome-file>
</welcome-file-list>
</web-app>
@cgp
Copy link

cgp commented Apr 13, 2013

I had the same problem and was frustrated by this for an hour or so before I realized that I use the runJettyRun plugin -- which is awesome, however, it allows you to select between the versions of Jetty pretty easily, and I had slipped up and selected Jetty 6. Needless to say, once I selected version 8 -- everything worked perfectly. Thank you for this wonderful simple example.

@xdylxdyl
Copy link

xdylxdyl commented Jun 6, 2013

if i use maven jetty:run. what version of jetty plugin i can use ?
i had the same problem .

@vgpetrov
Copy link

I have the same troubles with jetty:run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment