Skip to content

@ToddG /TimerWebSocketServlet.java
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
AngularJS + Jetty + WebSockett Example : TimerWebSocketServlet
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();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.