public
Last active

AngularJS + Jetty + WebSockett Example : TimerWebSocketServlet

  • Download Gist
TimerWebSocketServlet.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
 
public class TimerWebSocketServlet extends WebSocketServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
doSomething(req, resp);
}
 
void doSomething(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><head><title>TimerWebSocketServlet</title></head>");
out.println("<body><h1>I am a websocket...connect to me that way, silly</h1>");
out.println("</body></html>");
}
 
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
{
return new TimerWebSocket();
}
 
class TimerWebSocket implements WebSocket
{
Timer t;
 
public void onOpen(final Connection connection)
{
t = new Timer("foo");
t.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
try
{
final String s = new Date().toString();
connection.sendMessage(s);
System.out.println("sending: " + s);
} catch (IOException e)
{
e.printStackTrace();
}
}
}, 0, 5000);
}
 
public void onClose(final int i, final String s)
{
if(t !=null)
{
t.cancel();
}
}
 
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.