Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- import java.io.IOException;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import net.sourceforge.stripes.action.ActionBean;
- import net.sourceforge.stripes.action.ActionBeanContext;
- import net.sourceforge.stripes.action.DefaultHandler;
- import net.sourceforge.stripes.action.Resolution;
- import net.sourceforge.stripes.action.UrlBinding;
- import org.eclipse.jetty.websocket.WebSocket;
- import org.eclipse.jetty.websocket.WebSocketFactory;
- @UrlBinding( "/ws.action" )
- public class WebSocketActionBean implements ActionBean {
- private ActionBeanContext context;
- private static WebSocketFactory WSFACTORY;
- private static final Logger logger = Logger.getLogger( WebSocketActionBean.class.getName() );
- private class MyWebSocket implements WebSocket {
- private Outbound outbound;
- @Override
- public void onConnect( Outbound outbound ) {
- this.outbound = outbound;
- logger.info( "Connect" );
- }
- @Override
- public void onMessage( byte opcode, String data ) {
- try {
- // just echo message
- outbound.sendMessage( data );
- } catch ( IOException ex ) {
- logger.log( Level.SEVERE, null, ex );
- }
- logger.info( "Message" );
- }
- @Override
- public void onFragment( boolean more, byte opcode, byte[] data, int offset, int length ) {
- }
- @Override
- public void onMessage( byte opcode, byte[] data, int offset, int length ) {
- }
- @Override
- public void onDisconnect() {
- logger.info( "Disconnect" );
- }
- }
- static {
- WSFACTORY = new WebSocketFactory( 8192 );
- WSFACTORY.setMaxIdleTime( 300000 );
- }
- @Override
- public void setContext( ActionBeanContext context ) {
- this.context = context;
- }
- @Override
- public ActionBeanContext getContext() {
- return this.context;
- }
- @DefaultHandler
- public Resolution connect() {
- return new Resolution() {
- @Override
- public void execute( HttpServletRequest request, HttpServletResponse response ) throws Exception {
- if ( "WebSocket".equals( request.getHeader( "Upgrade" ) ) ) {
- boolean hixie = request.getHeader( "Sec-WebSocket-Key1" ) != null;
- String protocol = request.getHeader( hixie ? "Sec-WebSocket-Protocol" : "WebSocket-Protocol" );
- if ( protocol == null ) {
- protocol = request.getHeader( "Sec-WebSocket-Protocol" );
- }
- WebSocket ws = new MyWebSocket();
- String host = request.getHeader( "Host" );
- String origin = request.getHeader( "Origin" );
- if ( origin == null ) {
- origin = host;
- }
- WSFACTORY.upgrade( request, response, ws, origin, protocol );
- } else {
- throw new IllegalStateException( "No WebSocket request" );
- }
- }
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment