Created
June 12, 2011 21:04
-
-
Save manzke/1021982 to your computer and use it in GitHub Desktop.
Jetty 7+8 Web Socket Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
I had the same problem and i solved using jetty 8.10 version.
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.
if i use maven jetty:run. what version of jetty plugin i can use ?
i had the same problem .
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
Thx for this code. I have really pretty much the same, but currently get this error:
2013-02-05 11:42:02.270:INFO:oejs.Server:jetty-8.1.9.v20130131
2013-02-05 11:42:02.577:INFO:oejs.AbstractConnector:Started [email protected]:8080
2013-02-05 11:42:07.094:WARN:oejs.ServletHandler:/echo
java.lang.NullPointerException
at org.eclipse.jetty.websocket.WebSocketFactory.upgrade(WebSocketFactory.java:236)
at org.eclipse.jetty.websocket.WebSocketFactory.acceptWebSocket(WebSocketFactory.java:382)
at org.eclipse.jetty.websocket.WebSocketServlet.service(WebSocketServlet.java:104)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:669)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:457)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1075)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:384)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1009)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:368)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:488)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:932)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:994)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:640)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:628)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
at java.lang.Thread.run(Thread.java:722)
do you have any idea what I do wrong? why is the upgrade not working. Client is chrome/javascript right now.
thx
Svne