io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler Java Examples

The following examples show how to use io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EchoServerWS.java    From examples-javafx-repos1 with Apache License 2.0 6 votes vote down vote up
protected ChannelInitializer<Channel> createInitializer() {

	return new ChannelInitializer<Channel>() {

		@Override
		protected void initChannel(Channel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new HttpServerCodec() );
			p.addLast(new ChunkedWriteHandler());
			p.addLast(new HttpObjectAggregator(64 * 1024));
			p.addLast(new EchoServerHttpRequestHandler("/ws"));
			p.addLast(new WebSocketServerProtocolHandler("/ws"));
			p.addLast(new EchoServerWSHandler());
		}
	};
}
 
Example #2
Source File: NetworkServiceImpl.java    From ServerCore with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(Channel ch) {
    //添加web socket相关内容
    ChannelPipeline pip = ch.pipeline();
    if (sslCtx != null) {
        pip.addLast("sslHandler", sslCtx.newHandler(ch.alloc()));
    }
    pip.addLast(new HttpServerCodec());
    pip.addLast(new HttpObjectAggregator(65536));
    pip.addLast(new WebSocketServerProtocolHandler("/"));
    pip.addLast(new WebSocketDecoder());
    pip.addLast(new WebSocketEncoder());
    pip.addLast(new MessageDecoder(builder.getImessageandhandler()));
    pip.addLast(new MessageExecutor(builder.getConsumer(), builder.getListener()));
    for (ChannelHandler handler : builder.getExtraHandlers()) {
        pip.addLast(handler);
    }
}
 
Example #3
Source File: TextWebSocketFrameHandler.java    From netty-learning with MIT License 6 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE){
        //删除之前 HttpRequestHandle
        ctx.pipeline().remove(HttpRequestHandle.class) ;

        //通知所有已经连接的客户端 有新的连接来了
        group.writeAndFlush(new TextWebSocketFrame("新的客户端=" + ctx.channel() + "连接上来了")) ;

        //将当前的 channel 也就是 websocket channel 加入到 channelGroup 当中
        group.add(ctx.channel()) ;
    }else {
        //交给下一个 channelHandler 处理
        super.userEventTriggered(ctx, evt);
    }

}
 
Example #4
Source File: Balancer.java    From timely with Apache License 2.0 6 votes vote down vote up
protected ChannelHandler setupWSChannel(BalancerConfiguration balancerConfig, SslContext sslCtx,
        MetricResolver metricResolver, WsClientPool wsClientPool) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
            ch.pipeline().addLast("httpServer", new HttpServerCodec());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
            ch.pipeline().addLast("sessionExtractor", new WebSocketFullRequestHandler());

            ch.pipeline().addLast("idle-handler",
                    new IdleStateHandler(balancerConfig.getWebsocket().getTimeout(), 0, 0));
            ch.pipeline().addLast("ws-protocol",
                    new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, false, true));
            ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(balancerConfig.getSecurity()));
            ch.pipeline().addLast("httpRelay", new WsRelayHandler(balancerConfig, metricResolver, wsClientPool));
            ch.pipeline().addLast("error", new WSTimelyExceptionHandler());
        }
    };
}
 
Example #5
Source File: TtyServerInitializer.java    From termd with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(new HttpServerCodec());
  pipeline.addLast(new ChunkedWriteHandler());
  pipeline.addLast(new HttpObjectAggregator(64 * 1024));
  HttpRequestHandler httpRequestHandler = null;
      if (httpResourcePath == null) {
          httpRequestHandler = new HttpRequestHandler("/ws");
      } else {
          httpRequestHandler = new HttpRequestHandler("/ws", httpResourcePath);
      }

  pipeline.addLast(httpRequestHandler);
  pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
  pipeline.addLast(new TtyWebSocketFrameHandler(group, handler, HttpRequestHandler.class));
}
 
Example #6
Source File: WebSocketServerInitializer.java    From SpringMVC-Project with MIT License 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    //添加闲置处理,60秒没有数据传输,触发事件
    pipeline.addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
    //将字节解码为HttpMessage对象,并将HttpMessage对象编码为字节
    pipeline.addLast(new HttpServerCodec());
    //出站数据压缩
    pipeline.addLast(new HttpContentCompressor());
    //聚合多个HttpMessage为单个FullHttpRequest
    pipeline.addLast(new HttpObjectAggregator(64 * 1024));
    //如果被请求的端点是/ws,则处理该升级握手
    pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
    //聊天消息处理
    pipeline.addLast(new ChatServerHandler());
    //心跳处理
    pipeline.addLast(new HeartbeatHandler());
}
 
Example #7
Source File: HttpHandler.java    From bitchat with Apache License 2.0 6 votes vote down vote up
private boolean upgradeToWebSocket(ChannelHandlerContext ctx, FullHttpRequest request) {
    HttpHeaders headers = request.headers();
    if ("Upgrade".equalsIgnoreCase(headers.get(HttpHeaderNames.CONNECTION)) &&
            "WebSocket".equalsIgnoreCase(headers.get(HttpHeaderNames.UPGRADE))) {
        ChannelPipeline pipeline = ctx.pipeline();
        // 将http升级为WebSocket
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(FrameCodec.getInstance());
        pipeline.addLast(FrameHandler.getInstance(channelListener));
        pipeline.remove(this);
        // 将channelActive事件传递到FrameHandler
        ctx.fireChannelActive();
        return true;
    }
    return false;
}
 
Example #8
Source File: WebSocketInitializer.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
public void addHandlers(final Channel ch) {
    ch.pipeline().addBefore(AbstractChannelInitializer.FIRST_ABSTRACT_HANDLER, HTTP_SERVER_CODEC, new HttpServerCodec());
    ch.pipeline().addAfter(HTTP_SERVER_CODEC, HTTP_OBJECT_AGGREGATOR, new HttpObjectAggregator(WEBSOCKET_MAX_CONTENT_LENGTH));

    final String webSocketPath = websocketListener.getPath();
    final String subprotocols = getSubprotocolString();
    final boolean allowExtensions = websocketListener.getAllowExtensions();

    ch.pipeline().addAfter(HTTP_OBJECT_AGGREGATOR, WEBSOCKET_SERVER_PROTOCOL_HANDLER, new WebSocketServerProtocolHandler(webSocketPath, subprotocols, allowExtensions, Integer.MAX_VALUE));
    ch.pipeline().addAfter(WEBSOCKET_SERVER_PROTOCOL_HANDLER, WEBSOCKET_BINARY_FRAME_HANDLER, new WebSocketBinaryFrameHandler());
    ch.pipeline().addAfter(WEBSOCKET_BINARY_FRAME_HANDLER, WEBSOCKET_CONTINUATION_FRAME_HANDLER, new WebSocketContinuationFrameHandler());
    ch.pipeline().addAfter(WEBSOCKET_BINARY_FRAME_HANDLER, WEBSOCKET_TEXT_FRAME_HANDLER, new WebSocketTextFrameHandler());

    ch.pipeline().addAfter(WEBSOCKET_TEXT_FRAME_HANDLER, MQTT_WEBSOCKET_ENCODER, new MQTTWebsocketEncoder());

}
 
Example #9
Source File: WebsocketServer.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 6 votes vote down vote up
public ChannelFuture run() {

    final ServerBootstrap httpServerBootstrap = new ServerBootstrap();
    httpServerBootstrap.group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .localAddress(new InetSocketAddress(port))
      .childHandler(new ChannelInitializer<SocketChannel>() {

        public void initChannel(final SocketChannel ch) throws Exception {
          ch.pipeline().addLast(
            new HttpResponseEncoder(),
            new HttpRequestDecoder(),
            new HttpObjectAggregator(65536),
            new WebSocketServerProtocolHandler("/debug-session"),
            new DebugProtocolHandler(debugWebsocketConfiguration));
        }

    });

    LOGG.log(Level.INFO, "starting camunda BPM debug HTTP websocket interface on port "+port+".");

    return httpServerBootstrap.bind(port);


  }
 
Example #10
Source File: WebSocketInitializer.java    From jeesupport with MIT License 6 votes vote down vote up
@Override
	protected void initChannel( SocketChannel _channel ) throws Exception {
		ChannelPipeline pipeline = _channel.pipeline();

		// 是否使用客户端模式
		if( CommonConfig.getBoolean( "jees.jsts.websocket.ssl.enable", false ) ){
			SSLEngine engine = sslContext1.createSSLEngine();
//			 是否需要验证客户端
			engine.setUseClientMode(false);
//			engine.setNeedClientAuth(false);
			pipeline.addFirst("ssl", new SslHandler( engine ));
		}

		pipeline.addLast( new IdleStateHandler( 100 , 0 , 0 , TimeUnit.SECONDS ) );
		pipeline.addLast( new HttpServerCodec() );
		pipeline.addLast( new ChunkedWriteHandler() );
		pipeline.addLast( new HttpObjectAggregator( 8192 ) );
		pipeline.addLast( new WebSocketServerProtocolHandler( CommonConfig.getString( ISocketBase.Netty_WebSocket_Url, "/" ) ) );
		pipeline.addLast( CommonContextHolder.getBean( WebSocketHandler.class ) );
	}
 
Example #11
Source File: NewNettyAcceptor.java    From cassandana with Apache License 2.0 6 votes vote down vote up
private void initializeWebSocketTransport(final NewNettyMQTTHandler handler, Config conf) {
    LOG.debug("Configuring Websocket MQTT transport");
    if(!conf.websocketEnabled) {
    	return;
    }
    
    int port = conf.websocketPort;// Integer.parseInt(webSocketPortProp);

    final MoquetteIdleTimeoutHandler timeoutHandler = new MoquetteIdleTimeoutHandler();

    String host = conf.websocketHost;
    initFactory(host, port, "Websocket MQTT", new PipelineInitializer() {

        @Override
        void init(SocketChannel channel) {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new HttpServerCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
            pipeline.addLast("webSocketHandler",
                    new WebSocketServerProtocolHandler("/mqtt", MQTT_SUBPROTOCOL_CSV_LIST));
            pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
            pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
            configureMQTTPipeline(pipeline, timeoutHandler, handler);
        }
    });
}
 
Example #12
Source File: Server.java    From qonduit with Apache License 2.0 6 votes vote down vote up
protected ChannelHandler setupWSChannel(SslContext sslCtx, Configuration conf, DataStore datastore) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
            ch.pipeline().addLast("httpServer", new HttpServerCodec());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
            ch.pipeline().addLast("sessionExtractor", new WebSocketHttpCookieHandler(config));
            ch.pipeline().addLast("idle-handler", new IdleStateHandler(conf.getWebsocket().getTimeout(), 0, 0));
            ch.pipeline().addLast("ws-protocol", new WebSocketServerProtocolHandler(WS_PATH, null, true));
            ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(datastore, config));
            ch.pipeline().addLast("error", new WSExceptionHandler());
        }
    };

}
 
Example #13
Source File: WebSocketServerInitializer.java    From litchi with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new WebSocketServerCompressionHandler());
    pipeline.addLast(new IdleStateHandler(0, 0, 60));
    pipeline.addLast(new WebSocketServerProtocolHandler(WEB_SOCKET_PATH, null, true));
    pipeline.addLast(new WebSocketHandler(litchi));

    for (ChannelHandler handler : handlers) {
        pipeline.addLast(handler);
    }
}
 
Example #14
Source File: ServerChannelInitializer.java    From ThinkMap with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    pipeline.addLast("timeout", new ReadTimeoutHandler(15));
    pipeline.addLast("codec-http", new HttpServerCodec());
    pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
    pipeline.addLast("handler", new HTTPHandler(plugin));
    pipeline.addLast("websocket", new WebSocketServerProtocolHandler("/server"));
    pipeline.addLast("packet-decoder", new PacketDecoder());
    pipeline.addLast("packet-encoder", new PacketEncoder());
    pipeline.addLast("packet-handler", new ClientHandler(socketChannel, plugin));

    socketChannel.config().setAllocator(PooledByteBufAllocator.DEFAULT);

    plugin.getWebHandler().getChannelGroup().add(socketChannel);
}
 
Example #15
Source File: WebSocketServerInitializer.java    From util4j with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt)throws Exception {
	if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE)
	{//旧版本
		log.debug("excute webSocketHandComplete……");
		webSocketHandComplete(ctx);
		ctx.pipeline().remove(this);
		log.debug("excuted webSocketHandComplete:"+ctx.pipeline().toMap().toString());
		return;
	}
	if(evt instanceof HandshakeComplete)
	{//新版本
		HandshakeComplete hc=(HandshakeComplete)evt;
		log.debug("excute webSocketHandComplete……,HandshakeComplete="+hc);
		webSocketHandComplete(ctx);
		ctx.pipeline().remove(this);
		log.debug("excuted webSocketHandComplete:"+ctx.pipeline().toMap().toString());
		return;
	}
	super.userEventTriggered(ctx, evt);
}
 
Example #16
Source File: TtyServerInitializer.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(new HttpServerCodec());
  pipeline.addLast(new ChunkedWriteHandler());
  pipeline.addLast(new HttpObjectAggregator(64 * 1024));
  pipeline.addLast(new HttpRequestHandler("/ws"));
  pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
  pipeline.addLast(new TtyWebSocketFrameHandler(group, handler));
}
 
Example #17
Source File: WebsocketServer.java    From mpush with Apache License 2.0 5 votes vote down vote up
@Override
protected void initPipeline(ChannelPipeline pipeline) {
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new WebSocketServerCompressionHandler());
    pipeline.addLast(new WebSocketServerProtocolHandler(CC.mp.net.ws_path, null, true));
    pipeline.addLast(new WebSocketIndexPageHandler());
    pipeline.addLast(getChannelHandler());
}
 
Example #18
Source File: Server.java    From timely with Apache License 2.0 5 votes vote down vote up
protected ChannelHandler setupWSChannel(SslContext sslCtx, Configuration conf) {
    return new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", sslCtx.newHandler(ch.alloc()));
            ch.pipeline().addLast("httpServer", new HttpServerCodec());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
            ch.pipeline().addLast("sessionExtractor", new WebSocketFullRequestHandler());
            ch.pipeline().addLast("idle-handler", new IdleStateHandler(conf.getWebsocket().getTimeout(), 0, 0));
            ch.pipeline().addLast("ws-protocol",
                    new WebSocketServerProtocolHandler(WS_PATH, null, true, 65536, false, true));
            ch.pipeline().addLast("wsDecoder", new WebSocketRequestDecoder(config.getSecurity()));
            ch.pipeline().addLast("aggregators", new WSAggregatorsRequestHandler());
            ch.pipeline().addLast("metrics", new WSMetricsRequestHandler(config));
            ch.pipeline().addLast("query", new WSQueryRequestHandler(dataStore));
            ch.pipeline().addLast("lookup", new WSSearchLookupRequestHandler(dataStore));
            ch.pipeline().addLast("suggest", new WSSuggestRequestHandler(dataStore));
            ch.pipeline().addLast("version", new WSVersionRequestHandler());
            ch.pipeline().addLast("put", new WSMetricPutHandler(dataStore));
            ch.pipeline().addLast("create",
                    new WSCreateSubscriptionRequestHandler(dataStore, dataStoreCache, config));
            ch.pipeline().addLast("add", new WSAddSubscriptionRequestHandler());
            ch.pipeline().addLast("remove", new WSRemoveSubscriptionRequestHandler());
            ch.pipeline().addLast("close", new WSCloseSubscriptionRequestHandler());
            ch.pipeline().addLast("error", new WSTimelyExceptionHandler());
        }
    };

}
 
Example #19
Source File: WebSocketRequestDecoder.java    From timely with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof IdleStateEvent) {
        IdleStateEvent idle = (IdleStateEvent) evt;
        if (idle.state() == IdleState.READER_IDLE) {
            // We have not read any data from client in a while, let's close
            // the subscriptions for this context.
            String subscriptionId = ctx.channel().attr(SubscriptionRegistry.SUBSCRIPTION_ID_ATTR).get();
            if (!StringUtils.isEmpty(subscriptionId)) {
                if (SubscriptionRegistry.get().containsKey(subscriptionId)) {
                    LOG.info("Closing subscription with subscription id {} due to idle event", subscriptionId);
                    SubscriptionRegistry.get().get(subscriptionId).close();
                }
            } else {
                LOG.warn("Channel idle, but no subscription id found on context. Unable to close subscriptions");
            }
        }
    } else if (evt instanceof SslCompletionEvent) {
        LOG.debug("{}", ((SslCompletionEvent) evt).getClass().getSimpleName());
    } else if (evt instanceof WebSocketServerProtocolHandler.ServerHandshakeStateEvent) {
        // The handshake completed succesfully and the channel was upgraded to
        // websockets
        LOG.trace("SSL handshake completed successfully, upgraded channel to websockets");
    } else {
        LOG.warn("Received unhandled user event {}", evt);
    }
}
 
Example #20
Source File: NettyChannelInitializer.java    From ChatServer with Artistic License 2.0 5 votes vote down vote up
/**
 * 채널 파이프라인 설정.
 * Netty.Server.Configuration.NettyServerConfiguration 에서 등록한 Bean 을 이용해 사용자의 통신을 처리할 Handler 도 등록.
 * Netty.Server.Handler.JsonHandler 에서 실제 사용자 요청 처리.
 *
 * @param channel
 * @throws Exception
 */
@Override
protected void initChannel(Channel channel) throws Exception {

	ChannelPipeline channelPipeline = channel.pipeline();

	switch (transferType) {

		case "websocket":

			channelPipeline
					.addLast(new HttpServerCodec())
					.addLast(new HttpObjectAggregator(65536))
					.addLast(new WebSocketServerCompressionHandler())
					.addLast(new WebSocketServerProtocolHandler(transferWebsocketPath, transferWebsocketSubProtocol, transferWebsocketAllowExtensions))
					.addLast(new LoggingHandler(LogLevel.valueOf(logLevelPipeline)))
					.addLast(websocketHandler);

		case "tcp":
		default:

			channelPipeline
					.addLast(new LineBasedFrameDecoder(Integer.MAX_VALUE))
					.addLast(STRING_DECODER)
					.addLast(STRING_ENCODER)
					.addLast(new LoggingHandler(LogLevel.valueOf(logLevelPipeline)))
					.addLast(jsonHandler);

	}

}
 
Example #21
Source File: WebServerChannelInitializer.java    From lannister with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
	if ("true".equalsIgnoreCase(Settings.INSTANCE.getProperty("webserver.logging.writelogOfNettyLogger"))) {
		ch.pipeline().addLast("log", new LoggingHandler("lannister.web/server", LogLevel.DEBUG));
	}

	if (useSsl) {
		SslContext sslCtx = SslContextBuilder
				.forServer(Settings.INSTANCE.certChainFile(), Settings.INSTANCE.privateKeyFile()).build();

		logger.debug("SSL Provider : {}", SslContext.defaultServerProvider());

		ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
	}

	ch.pipeline().addLast(HttpServerCodec.class.getName(), new HttpServerCodec());
	ch.pipeline().addLast(HttpObjectAggregator.class.getName(), new HttpObjectAggregator(1048576));
	ch.pipeline().addLast(HttpContentCompressor.class.getName(), new HttpContentCompressor());
	ch.pipeline().addLast(HttpRequestRouter.class.getName(), new HttpRequestRouter());

	if (websocketFrameHandlerClass != null) {
		WebsocketFrameHandler wsfh = websocketFrameHandlerClass.newInstance();

		ch.pipeline().addLast(WebSocketServerProtocolHandler.class.getName(), new WebSocketServerProtocolHandler(
				wsfh.websocketPath(), wsfh.subprotocols(), wsfh.allowExtensions(), wsfh.maxFrameSize()));

		ch.pipeline().addLast(wsfh);
	}
}
 
Example #22
Source File: WebSocketRemoteServerInitializer.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpServerCodec());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new WebSocketServerCompressionHandler());
    pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, subProtocols, true));
    pipeline.addLast(new WebSocketRemoteServerFrameHandler());
}
 
Example #23
Source File: NettyAcceptor.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 5 votes vote down vote up
private void initializeWebSocketTransport(IMessaging messaging, Properties props)
    throws IOException {
  String webSocketPortProp = props.getProperty(Constants.WEB_SOCKET_PORT_PROPERTY_NAME);
  if (webSocketPortProp == null) {
    //Do nothing no WebSocket configured
    LOG.info("WebSocket is disabled");
    return;
  }
  int port = Integer.parseInt(webSocketPortProp);

  final NettyMQTTHandler mqttHandler = new NettyMQTTHandler();
  final PubsubHandler handler = new PubsubHandler(pubsub, mqttHandler);
  handler.setMessaging(messaging);

  String host = props.getProperty(Constants.HOST_PROPERTY_NAME);
  initFactory(host, port, new PipelineInitializer() {
    @Override
    void init(ChannelPipeline pipeline) {
      pipeline.addLast("httpEncoder", new HttpResponseEncoder());
      pipeline.addLast("httpDecoder", new HttpRequestDecoder());
      pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
      pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler("/mqtt"/*"/mqtt"*/,
          "mqttv3.1, mqttv3.1.1"));
      //pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler(null, "mqtt"));
      pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
      pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
      pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0,
          Constants.DEFAULT_CONNECT_TIMEOUT));
      pipeline.addAfter("idleStateHandler", "idleEventHandler", new MoquetteIdleTimeoutHandler());
      pipeline.addFirst("bytemetrics", new BytesMetricsHandler(bytesMetricsCollector));
      pipeline.addLast("decoder", new MQTTDecoder());
      pipeline.addLast("encoder", new MQTTEncoder());
      pipeline.addLast("metrics", new MessageMetricsHandler(metricsCollector));
      pipeline.addLast("handler", handler);
    }
  });
}
 
Example #24
Source File: NettyAcceptor.java    From cloud-pubsub-mqtt-proxy with Apache License 2.0 5 votes vote down vote up
private void initializeWssTransport(IMessaging messaging, Properties props,
    final SslHandler sslHandler) throws IOException {
  String sslPortProp = props.getProperty(Constants.WSS_PORT_PROPERTY_NAME);
  if (sslPortProp == null) {
    //Do nothing no SSL configured
    LOG.info("SSL is disabled");
    return;
  }
  int sslPort = Integer.parseInt(sslPortProp);
  final NettyMQTTHandler mqttHandler = new NettyMQTTHandler();
  final PubsubHandler handler = new PubsubHandler(pubsub, mqttHandler);
  handler.setMessaging(messaging);
  String host = props.getProperty(Constants.HOST_PROPERTY_NAME);
  initFactory(host, sslPort, new PipelineInitializer() {
    @Override
    void init(ChannelPipeline pipeline) throws Exception {
      pipeline.addLast("ssl", sslHandler);
      pipeline.addLast("httpEncoder", new HttpResponseEncoder());
      pipeline.addLast("httpDecoder", new HttpRequestDecoder());
      pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
      pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler("/mqtt",
          "mqttv3.1, mqttv3.1.1"));
      pipeline.addLast("ws2bytebufDecoder", new WebSocketFrameToByteBufDecoder());
      pipeline.addLast("bytebuf2wsEncoder", new ByteBufToWebSocketFrameEncoder());
      pipeline.addFirst("idleStateHandler", new IdleStateHandler(0, 0,
          Constants.DEFAULT_CONNECT_TIMEOUT));
      pipeline.addAfter("idleStateHandler", "idleEventHandler", new MoquetteIdleTimeoutHandler());
      pipeline.addFirst("bytemetrics", new BytesMetricsHandler(bytesMetricsCollector));
      pipeline.addLast("decoder", new MQTTDecoder());
      pipeline.addLast("encoder", new MQTTEncoder());
      pipeline.addLast("metrics", new MessageMetricsHandler(metricsCollector));
      pipeline.addLast("handler", handler);
    }
  });
}
 
Example #25
Source File: TtyServerInitializer.java    From arthas with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {

  ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(new HttpServerCodec());
  pipeline.addLast(new ChunkedWriteHandler());
  pipeline.addLast(new HttpObjectAggregator(64 * 1024));
  pipeline.addLast(workerGroup, "HttpRequestHandler", new HttpRequestHandler("/ws", new File("arthas-output")));
  pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
  pipeline.addLast(new TtyWebSocketFrameHandler(group, handler));
}
 
Example #26
Source File: TtyWebSocketFrameHandler.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
    ctx.pipeline().remove(HttpRequestHandler.class);
    group.add(ctx.channel());
    conn = new HttpTtyConnection() {
      @Override
      protected void write(byte[] buffer) {
        ByteBuf byteBuf = Unpooled.buffer();
        byteBuf.writeBytes(buffer);
        context.writeAndFlush(new TextWebSocketFrame(byteBuf));
      }

      public void schedule(Runnable task, long delay, TimeUnit unit) {
        context.executor().schedule(task, delay, unit);
      }

      public void execute(Runnable task) {
        context.executor().execute(task);
      }

      @Override
      public void close() {
        context.close();
      }
    };
    handler.accept(conn);
  } else {
    super.userEventTriggered(ctx, evt);
  }
}
 
Example #27
Source File: DebugProtocolHandler.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  if(evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
    // open the session
    debugWebsocketConfiguration
      .getProtocol()
      .openSession(ctx);
  }
  super.userEventTriggered(ctx, evt);
}
 
Example #28
Source File: TtyServerInitializer.java    From termd with Apache License 2.0 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipeline = ch.pipeline();
  pipeline.addLast(new HttpServerCodec());
  pipeline.addLast(new ChunkedWriteHandler());
  pipeline.addLast(new HttpObjectAggregator(64 * 1024));
  pipeline.addLast(new HttpRequestHandler("/ws"));
  pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
  pipeline.addLast(new TtyWebSocketFrameHandler(group, handler));
}
 
Example #29
Source File: SampleWebSocketPushChannelInitializer.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
protected void addPushHandlers(final ChannelPipeline pipeline) {
    pipeline.addLast(PushAuthHandler.NAME, pushAuthHandler);
    pipeline.addLast(new WebSocketServerCompressionHandler());
    pipeline.addLast(new WebSocketServerProtocolHandler(PushProtocol.WEBSOCKET.getPath(), null, true));
    pipeline.addLast(new PushRegistrationHandler(pushConnectionRegistry, PushProtocol.WEBSOCKET));
    pipeline.addLast(new SampleWebSocketPushClientProtocolHandler());
}
 
Example #30
Source File: DFSocketManager.java    From dfactor with MIT License 5 votes vote down vote up
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
	if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
           ctx.pipeline().remove(DFWSRequestHandler.class);  //remove http handle
       } else {
           super.userEventTriggered(ctx, evt);
       }
}