List of usage examples for io.netty.handler.codec.http.websocketx WebSocketServerHandshaker handshake
public ChannelFuture handshake(Channel channel, HttpRequest req)
From source file:catacumba.websocket.internal.WebSocketEngine.java
License:Apache License
@SuppressWarnings("deprecation") public static <T> void connect(final Context context, String path, int maxLength, final WebSocketHandler<T> handler) { PublicAddress publicAddress = context.get(PublicAddress.class); URI address = publicAddress.get(context); URI httpPath = address.resolve(path); URI wsPath;/*w ww . j ava 2s .com*/ try { wsPath = new URI("ws", httpPath.getUserInfo(), httpPath.getHost(), httpPath.getPort(), httpPath.getPath(), httpPath.getQuery(), httpPath.getFragment()); } catch (URISyntaxException e) { throw uncheck(e); } WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(wsPath.toString(), null, true, maxLength); Request request = context.getRequest(); HttpMethod method = valueOf(request.getMethod().getName()); FullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri()); nettyRequest.headers().add(SEC_WEBSOCKET_VERSION, request.getHeaders().get(SEC_WEBSOCKET_VERSION)); nettyRequest.headers().add(SEC_WEBSOCKET_KEY, request.getHeaders().get(SEC_WEBSOCKET_KEY)); final WebSocketServerHandshaker handshaker = factory.newHandshaker(nettyRequest); final DirectChannelAccess directChannelAccess = context.getDirectChannelAccess(); final Channel channel = directChannelAccess.getChannel(); if (!channel.config().isAutoRead()) { channel.config().setAutoRead(true); } handshaker.handshake(channel, nettyRequest) .addListener(new HandshakeFutureListener<>(context, handshaker, handler)); }
From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java
License:Apache License
private void handshake(ChannelHandlerContext ctx, final UUID sessionId, String path, FullHttpRequest req) { final Channel channel = ctx.channel(); WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, false, configuration.getMaxFramePayloadLength()); WebSocketServerHandshaker handshaker = factory.newHandshaker(req); if (handshaker != null) { ChannelFuture f = handshaker.handshake(channel, req); f.addListener(new ChannelFutureListener() { @Override/*from www. j av a 2 s. c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.error("Can't handshake " + sessionId, future.cause()); return; } channel.pipeline().addBefore(SocketIOChannelInitializer.WEB_SOCKET_TRANSPORT, SocketIOChannelInitializer.WEB_SOCKET_AGGREGATOR, new WebSocketFrameAggregator(configuration.getMaxFramePayloadLength())); connectClient(channel, sessionId); } }); } else { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } }
From source file:com.zhucode.longio.transport.netty.HttpHandler.java
License:Open Source License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws ProtocolException { HttpHeaders headers = req.headers(); AttributeKey<Boolean> isWs = AttributeKey.valueOf("isWs"); String upgrade = headers.get("Upgrade"); String connection = headers.get("Connection"); if (upgrade != null && upgrade.equalsIgnoreCase("websocket") && connection != null && connection.equalsIgnoreCase("Upgrade")) { // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, true); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else {/*w w w . j ava 2s .c om*/ handshaker.handshake(ctx.channel(), req); AttributeKey<WebSocketServerHandshaker> key = AttributeKey.valueOf("WebSocketServerHandshaker"); ctx.attr(key).set(handshaker); } ctx.attr(isWs).set(true); } else { ctx.attr(isWs).set(false); if (HttpHeaders.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean ka = HttpHeaders.isKeepAlive(req); ctx.attr(keepAlive).set(ka); ByteBuf buf = req.content(); process(ctx, buf); } }
From source file:freddo.dtalk2.broker.netty.NettyBrokerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { LOG.trace(">>> handleHttpRequest: {}", req.getUri()); if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from ww w.ja v a 2 s. com } if (req.getMethod() == HttpMethod.GET && req.getUri().startsWith(DTalk.DTALKSRV_PATH)) { // // DTalk WebSocket Handshake // WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(req), null, true); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); synchronized (mChannelMapper) { NettyChannel channel = new NettyChannel(ctx, handshaker); channel.setIdleTime(60); mChannelMapper.put(ctx, channel); } } } else { // // HTTP Request // } }
From source file:io.cettia.asity.bridge.netty4.AsityServerCodec.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (!accept(req)) { ctx.fireChannelRead(msg);/*from www .j a va 2 s. com*/ return; } if (req.getMethod() == HttpMethod.GET && req.headers().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true)) { // Because WebSocketServerHandshaker requires FullHttpRequest FullHttpRequest wsRequest = new DefaultFullHttpRequest(req.getProtocolVersion(), req.getMethod(), req.getUri()); wsRequest.headers().set(req.headers()); wsReqMap.put(ctx.channel(), wsRequest); // Set timeout to avoid memory leak ctx.pipeline().addFirst(new ReadTimeoutHandler(5)); } else { NettyServerHttpExchange http = new NettyServerHttpExchange(ctx, req); httpMap.put(ctx.channel(), http); httpActions.fire(http); } } else if (msg instanceof HttpContent) { FullHttpRequest wsReq = wsReqMap.get(ctx.channel()); if (wsReq != null) { wsReq.content().writeBytes(((HttpContent) msg).content()); if (msg instanceof LastHttpContent) { wsReqMap.remove(ctx.channel()); // Cancel timeout ctx.pipeline().remove(ReadTimeoutHandler.class); WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory( getWebSocketLocation(ctx.pipeline(), wsReq), null, true); WebSocketServerHandshaker handshaker = factory.newHandshaker(wsReq); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), wsReq); NettyServerWebSocket ws = new NettyServerWebSocket(ctx, wsReq, handshaker); wsMap.put(ctx.channel(), ws); wsActions.fire(ws); } } } else { NettyServerHttpExchange http = httpMap.get(ctx.channel()); if (http != null) { http.handleChunk((HttpContent) msg); } } } else if (msg instanceof WebSocketFrame) { NettyServerWebSocket ws = wsMap.get(ctx.channel()); if (ws != null) { ws.handleFrame((WebSocketFrame) msg); } } }
From source file:io.haze.transport.tcp.websocket.WebSocketFrameDecoder.java
License:Apache License
/** * Handle the initial HTTP request and execute the web socket handshake. * * @param context The channel handler context. * @param request The HTTP request./* w w w . jav a2s . c o m*/ * @param messages The output messages. * * @throws Exception If an error has occurred. */ private void handleHTTP(ChannelHandlerContext context, FullHttpRequest request, List<Object> messages) throws Exception { WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory( String.format("ws://%s/", request.headers().get(Names.HOST)), null, false); WebSocketServerHandshaker handshaker = handshakerFactory.newHandshaker(request); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(context.channel()); } else { InetSocketAddress address = ((SocketChannel) context.channel()).remoteAddress(); handshakers.put(address, handshaker); handshaker.handshake(context.channel(), request); } }
From source file:io.liveoak.container.protocols.websocket.WebSocketHandshakerHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { DefaultHttpRequest req = (DefaultHttpRequest) msg; String upgrade = req.headers().get(HttpHeaders.Names.UPGRADE); if (HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(upgrade)) { // ensure FullHttpRequest by installing HttpObjectAggregator in front of this handler ReferenceCountUtil.retain(msg); this.configurator.switchToWebSocketsHandshake(ctx.pipeline()); ctx.pipeline().fireChannelRead(msg); } else {/*from ww w. j a v a 2 s . co m*/ ReferenceCountUtil.retain(msg); this.configurator.switchToPlainHttp(ctx.pipeline()); ctx.pipeline().fireChannelRead(msg); } } else { // do the handshake FullHttpRequest req = (FullHttpRequest) msg; WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.getUri(), null, false); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { ChannelFuture future = handshaker.handshake(ctx.channel(), req); future.addListener(f -> { this.configurator.switchToWebSockets(ctx.pipeline()); }); } } }
From source file:io.reactivex.netty.protocol.http.websocket.WebSocketServerHandler.java
License:Apache License
private ChannelFuture handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_FAILURE); return null; }/*from w w w.j a va 2s .c om*/ // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); eventsSubject.onEvent(WebSocketServerMetricsEvent.HANDSHAKE_FAILURE); return null; } // Handshake WebSocketServerHandshaker handshaker = handshakeHandlerFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); return null; } return handshaker.handshake(ctx.channel(), req); }
From source file:io.scalecube.socketio.pipeline.WebSocketHandler.java
License:Apache License
private boolean handshake(final ChannelHandlerContext ctx, final FullHttpRequest req, final String requestPath) { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, false, maxWebSocketFrameSize); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker != null) { handshaker.handshake(ctx.channel(), req).addListener(new ChannelFutureListener() { @Override/*from www .j a v a 2s . c om*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { final String sessionId = PipelineUtils.getSessionId(requestPath); connect(ctx, req, sessionId); } } }); return true; } else { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } return false; }
From source file:io.vertx.core.http.impl.Http1xServerConnection.java
License:Open Source License
ServerWebSocketImpl createWebSocket(HttpServerRequestImpl request) {
if (ws != null) {
return ws;
}/*from w w w . j ava 2 s . c o m*/
if (!(request.getRequest() instanceof FullHttpRequest)) {
throw new IllegalStateException();
}
FullHttpRequest nettyReq = (FullHttpRequest) request.getRequest();
WebSocketServerHandshaker handshaker = createHandshaker(nettyReq);
if (handshaker == null) {
throw new IllegalStateException("Can't upgrade this request");
}
Function<ServerWebSocketImpl, String> f = ws -> {
try {
handshaker.handshake(chctx.channel(), nettyReq);
} catch (WebSocketHandshakeException e) {
handleException(e);
} catch (Exception e) {
log.error("Failed to generate shake response", e);
}
// remove compressor as its not needed anymore once connection was upgraded to websockets
ChannelHandler handler = chctx.pipeline().get(HttpChunkContentCompressor.class);
if (handler != null) {
chctx.pipeline().remove(handler);
}
if (METRICS_ENABLED && metrics != null) {
ws.setMetric(metrics.upgrade(request.metric(), ws));
}
ws.registerHandler(vertx.eventBus());
return handshaker.selectedSubprotocol();
};
ws = new ServerWebSocketImpl(vertx, request.uri(), request.path(), request.query(), request.headers(), this,
handshaker.version() != WebSocketVersion.V00, f, options.getMaxWebsocketFrameSize(),
options.getMaxWebsocketMessageSize());
return ws;
}