-
-
Save gerzhan/7000762 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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