List of usage examples for io.netty.handler.codec.http.websocketx WebSocketServerHandshaker close
public ChannelFuture close(Channel channel, CloseWebSocketFrame frame)
From source file:com.zhucode.longio.transport.netty.HttpHandler.java
License:Open Source License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws ProtocolException { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { AttributeKey<WebSocketServerHandshaker> key = AttributeKey.valueOf("WebSocketServerHandshaker"); WebSocketServerHandshaker handshaker = ctx.attr(key).get(); handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return;/*from ww w. j a v a2 s . com*/ } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } ByteBuf buf = ((TextWebSocketFrame) frame).content(); process(ctx, buf); }
From source file:io.haze.transport.tcp.websocket.WebSocketFrameDecoder.java
License:Apache License
/** * Handle a web socket frame./*w w w .j ava2 s . co m*/ * * @param context The channel handler context. * @param frame The web socket frame. * @param messages The output messages. * * @throws Exception If an error has occurred. */ private void handleWebSocket(ChannelHandlerContext context, WebSocketFrame frame, List<Object> messages) throws Exception { if (frame instanceof TextWebSocketFrame || frame instanceof BinaryWebSocketFrame) { messages.add(frame.content().retain()); } else if (frame instanceof CloseWebSocketFrame) { InetSocketAddress address = ((SocketChannel) context.channel()).remoteAddress(); WebSocketServerHandshaker handshaker = handshakers.remove(address); handshaker.close(context.channel(), (CloseWebSocketFrame) frame.retain()); } else if (frame instanceof PingWebSocketFrame) { context.writeAndFlush(new PongWebSocketFrame()); } }
From source file:nikoladasm.aspark.server.ServerHandler.java
License:Open Source License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { WebSocketContextImpl wctx = ctx.channel().attr(WEBSOCKET_CONTEXT_ATTR_KEY).get(); WebSocketHandler wsHandler = ctx.channel().attr(WEBSOCKET_HANDLER_ATTR_KEY).get(); if (frame instanceof CloseWebSocketFrame) { WebSocketServerHandshaker handshaker = ctx.channel().attr(HANDSHAKER_ATTR_KEY).get(); if (handshaker != null) { frame.retain();// w w w .j a v a 2 s . c o m handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame); if (wsHandler != null) { ctx.channel().attr(WEBSOCKET_HANDLER_ATTR_KEY).remove(); ctx.channel().attr(WEBSOCKET_CONTEXT_ATTR_KEY).remove(); String reason = ((CloseWebSocketFrame) frame).reasonText(); int statusCode = ((CloseWebSocketFrame) frame).statusCode(); wsHandler.onClose(wctx, statusCode, reason); } } else { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } return; } if (wsHandler == null) return; if (frame instanceof PingWebSocketFrame) { frame.content().retain(); ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content())); return; } if (frame instanceof PongWebSocketFrame) { return; } if (frame instanceof TextWebSocketFrame) { wctx.textFrameBegin(true); String request = ((TextWebSocketFrame) frame).text(); if (frame.isFinalFragment()) { wsHandler.onMessage(wctx, request); } else { wctx.stringBuilder().append(request); } return; } if (frame instanceof BinaryWebSocketFrame) { wctx.textFrameBegin(false); byte[] request = new byte[((BinaryWebSocketFrame) frame).content().readableBytes()]; ((BinaryWebSocketFrame) frame).content().readBytes(request); if (frame.isFinalFragment()) { wsHandler.onMessage(wctx, request); } else { wctx.frameBuffer().writeBytes(request); } return; } if (frame instanceof ContinuationWebSocketFrame) { if (wctx.textFrameBegin()) { String request = ((ContinuationWebSocketFrame) frame).text(); wctx.stringBuilder().append(request); if (frame.isFinalFragment()) { wsHandler.onMessage(wctx, wctx.stringBuilder().toString()); wctx.stringBuilder(new StringBuilder()); } } else { byte[] request = new byte[((BinaryWebSocketFrame) frame).content().readableBytes()]; ((BinaryWebSocketFrame) frame).content().readBytes(request); wctx.frameBuffer().writeBytes(request); if (frame.isFinalFragment()) { request = new byte[wctx.frameBuffer().readableBytes()]; wctx.frameBuffer().readBytes(request); wsHandler.onMessage(wctx, request); wctx.frameBuffer().clear(); } } return; } }
From source file:org.animotron.bridge.http.websocket.WebSocketHandler.java
License:Open Source License
public void close(WebSocketServerHandshaker hs, ChannelHandlerContext ctx, CloseWebSocketFrame frame) { hs.close(ctx.channel(), frame.retain()); }
From source file:org.animotron.bridge.http.WebSocketUpgradeHttpHandler.java
License:Open Source License
@Override public boolean handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Throwable { if (!request.getUri().equals(uriContext)) return false; if (!request.getMethod().equals(GET)) { HttpErrorHelper.handle(ctx, request, METHOD_NOT_ALLOWED); return true; }/*from w w w .j a v a 2 s . com*/ if (!"websocket".equals(getHeader(request, UPGRADE))) { sendStatus(ctx, UPGRADE_REQUIRED); return true; } WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(request), getProtocol(request), false); WebSocketServerHandshaker hs = wsFactory.newHandshaker(request); if (hs == null) { sendUnsupportedWebSocketVersionResponse(ctx.channel()); return true; } WebSocketHandler handler = selectHandler(getProtocol(request)); if (handler == null) { hs.handshake(ctx.channel(), request); hs.close(ctx.channel(), new CloseWebSocketFrame()); return true; } handler.open(hs, ctx); ctx.pipeline().removeLast(); ctx.pipeline().addLast(new WebSocketServerHandler(handler, hs)); hs.handshake(ctx.channel(), request); return true; }
From source file:org.pidome.server.system.network.http.HttpWebSocketHandler.java
/** * Handles incoming websocket frames.// ww w . j a v a 2s . co m * * @param handshaker Websocket handshake handler. * @param ctx The Channel handler. * @param frame A webosckert frame. * @throws UnsupportedOperationException When a websocket frame is not a * text based frame. */ protected static void handleWebSocketFrame(WebSocketServerHandshaker handshaker, ChannelHandlerContext ctx, WebSocketFrame frame) throws UnsupportedOperationException { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); finish(ctx); LOG.debug("Closed websocket channel: {}", frame); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); LOG.debug("ping/pong websocket channel: {}", frame); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException( String.format("%s frame type not supported", frame.getClass().getName())); } String request = ((TextWebSocketFrame) frame).text(); PidomeJSONRPC pidomeJSONRPC; try { if (request != null && !request.isEmpty()) { pidomeJSONRPC = new PidomeJSONRPC(URLDecoder.decode(request, "UTF-8")); Map<String, Object> result = new HashMap<>(); Map<String, Object> data = new HashMap<>(); result.put("success", true); result.put("message", ""); if (!isAuthorized(ctx)) { data.put("key", ""); data.put("auth", false); try { if (pidomeJSONRPC.getMethod().equals("ClientService.signOff")) { ctx.channel().disconnect(); finish(ctx); } else if (pidomeJSONRPC.getMethod().equals("ClientService.resume")) { WebsocketConsumer client = new WebsocketConsumer(ctx); PiDomeJSONRPCAuthentificationParameters authObjects = pidomeJSONRPC .getAuthenticationParameters(); if (authObjects.getKey() != null) { for (RemoteClient remoteClient : RemoteClientsConnectionPool .getConnectedClients()) { if (remoteClient.getKey().equals(authObjects.getKey())) { PersonsManagement.getInstance().getPersonByRemoteClient(remoteClient) .addRemoteClient(client); authUsers.add(client); data.put("code", 200); data.put("auth", true); data.put("message", "Authorized by legal web user."); LOG.debug("Client at {} is authorized as client for web interface", client.getRemoteSocketAddress()); break; } } if (!data.containsKey("code") || (int) data.get("code") != 200) { data.put("code", 401); data.put("message", "Authentication failed"); LOG.warn("Client at {} is not authorized as client for web interface", client.getRemoteSocketAddress()); } } else { data.put("code", 401); data.put("message", "Authentication failed"); LOG.error("Client at {} is not authorized is missing client key", client.getRemoteSocketAddress()); } } else if (!pidomeJSONRPC.getMethod().equals("ClientService.signOn")) { throw new AuthenticationException("Not authorized"); } else if (pidomeJSONRPC.getMethod().equals("ClientService.signOn")) { WebsocketConsumer client = new WebsocketConsumer(ctx); PiDomeJSONRPCAuthentificationParameters authObjects = pidomeJSONRPC .getAuthenticationParameters(); RemoteClientsAuthentication.AuthResult authResult = RemoteClientsAuthentication .authenticateWebsocketClient(client, authObjects); switch (authResult) { case OK: data.put("auth", true); data.put("code", 200); data.put("throttled", client.throttled()); data.put("key", client.getKey()); data.put("message", "Authentication ok"); authUsers.add(client); LOG.info("Client at {} is authorized as {}", client.getRemoteSocketAddress(), client.getClientName()); broadcastSignon(client); break; case WAIT: data.put("auth", true); data.put("code", 202); data.put("key", client.getKey()); data.put("message", "Authentication needs to be verified"); LOG.info("Client at {} needs to be authorized", client.getRemoteSocketAddress(), client.getClientName()); RemoteClientsConnectionPool.addWaitingDevice(client.getClientName(), client); break; default: data.put("code", 401); data.put("message", "Authentication failed"); LOG.info("Client at {} is not authorized as {}", client.getRemoteSocketAddress(), client.getClientName()); break; } } else { throw new PidomeJSONRPCException(PidomeJSONRPCException.JSONError.INVALID_REQUEST); } } catch (AuthenticationException ex) { data.put("code", 401); data.put("message", ex.getMessage()); } try { Thread.sleep(200); /// Sometimes We are to fast for some mobiles confirming/denying access. } catch (InterruptedException ex) { LOG.error("Could not wait for sending to {}: {}", ctx.channel().remoteAddress(), ex.getMessage()); } result.put("data", data); LOG.debug("Sending auth result {} to {}", pidomeJSONRPC.constructResponse(result), ctx.channel().remoteAddress()); ctx.channel().write(new TextWebSocketFrame(pidomeJSONRPC.constructResponse(result))); } else { boolean found = false; for (WebsocketConsumer client : authUsers) { if (client.isSocket(ctx)) { found = true; pidomeJSONRPC.handle(RemoteClientsConnectionPool.getClientBaseByConnection(client), client); ctx.channel().write(new TextWebSocketFrame(pidomeJSONRPC.getResult())); } } if (!found) throw new PidomeJSONRPCException(PidomeJSONRPCException.JSONError.INVALID_REQUEST); } } else { throw new PidomeJSONRPCException(PidomeJSONRPCException.JSONError.INVALID_REQUEST); } } catch (PidomeJSONRPCException ex) { LOG.error("Problem with JSON-RPC: {}", ex.getMessage(), ex); ctx.channel().write(new TextWebSocketFrame(ex.getJsonReadyMessage())); } catch (UnsupportedEncodingException ex) { ctx.channel() .write(new TextWebSocketFrame("{\"jsonrpc\": \"2.0\", \"error\": {\"code\": " + PidomeJSONRPCException.JSONError.PARSE_ERROR.toLong() + ", \"message\": \"Parse error, could not encode url: " + ex.getMessage() + "\"}, \"id\": null}")); } catch (Exception ex) { LOG.error("Error in handling JSON-RPC requests (send/receive): {}", ex.getMessage(), ex); ctx.channel() .write(new TextWebSocketFrame("{\"jsonrpc\": \"2.0\", \"error\": {\"code\": " + PidomeJSONRPCException.JSONError.SERVER_ERROR.toLong() + ", \"message\": \"an internal server error occurred: " + ex.getMessage() + "\"}, \"id\": null}")); } LOG.info("{} received {}", ctx.channel(), request); }
From source file:org.wso2.carbon.transport.http.netty.contractimpl.websocket.message.WebSocketInitMessageImpl.java
License:Open Source License
@Override public void cancelHandShake(int closeCode, String closeReason) { try {/*from w w w. j av a 2 s . c o m*/ WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketURL(httpRequest), getSubProtocol(), true); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(httpRequest); ChannelFuture channelFuture = handshaker.close(ctx.channel(), new CloseWebSocketFrame(closeCode, closeReason)); channelFuture.channel().close(); } finally { isCancelled = true; } }
From source file:org.wso2.carbon.transport.http.netty.contractimpl.websocket.message.WebSocketInitMessageImpl.java
License:Open Source License
private HandshakeFuture handleHandshake(WebSocketServerHandshaker handshaker, int idleTimeout) { HandshakeFutureImpl handshakeFuture = new HandshakeFutureImpl(); if (isCancelled) { Throwable e = new IllegalAccessException("Handshake is already cancelled!"); handshakeFuture.notifyError(e);/* w w w.ja v a 2s . com*/ return handshakeFuture; } try { ChannelFuture future = handshaker.handshake(ctx.channel(), httpRequest); handshakeFuture.setChannelFuture(future); future.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { String selectedSubProtocol = handshaker.selectedSubprotocol(); webSocketSourceHandler.setNegotiatedSubProtocol(selectedSubProtocol); setSubProtocol(selectedSubProtocol); WebSocketSessionImpl session = (WebSocketSessionImpl) getChannelSession(); session.setIsOpen(true); session.setNegotiatedSubProtocol(selectedSubProtocol); //Replace HTTP handlers with new Handlers for WebSocket in the pipeline ChannelPipeline pipeline = ctx.pipeline(); if (idleTimeout > 0) { pipeline.replace(Constants.IDLE_STATE_HANDLER, Constants.IDLE_STATE_HANDLER, new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS)); } else { pipeline.remove(Constants.IDLE_STATE_HANDLER); } pipeline.addLast(Constants.WEBSOCKET_SOURCE_HANDLER, webSocketSourceHandler); pipeline.remove(Constants.HTTP_SOURCE_HANDLER); setProperty(Constants.SRC_HANDLER, webSocketSourceHandler); handshakeFuture.notifySuccess(webSocketSourceHandler.getChannelSession()); } }); return handshakeFuture; } catch (Exception e) { /* Code 1002 : indicates that an endpoint is terminating the connection due to a protocol error. */ handshaker.close(ctx.channel(), new CloseWebSocketFrame(1002, "Terminating the connection due to a protocol error.")); handshakeFuture.notifyError(e); return handshakeFuture; } }
From source file:snow.http.server.WebSocketUpgradeHttpHandler.java
License:Open Source License
@Override public boolean handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Throwable { if (!request.getUri().equals(uriContext)) return false; if (!request.getMethod().equals(GET)) { HttpErrorHelper.handle(ctx, request, METHOD_NOT_ALLOWED); return true; }/*from ww w .j av a2 s.co m*/ try (Session session = SessionRegistry._.restorySession(request)) { // if (session == null || !session.isAuthorized()) { // HttpErrorHelper.handle(ctx, request, FORBIDDEN); // return true; // } if (!"websocket".equals(getHeader(request, UPGRADE))) { sendStatus(ctx, UPGRADE_REQUIRED); return true; } WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(request), getProtocol(request), false); WebSocketServerHandshaker hs = wsFactory.newHandshaker(request); if (hs == null) { sendUnsupportedWebSocketVersionResponse(ctx.channel()); return true; } WebSocketHandler<WebSocketFrame> handler = selectHandler(getProtocol(request)); if (handler == null) { hs.handshake(ctx.channel(), request); hs.close(ctx.channel(), new CloseWebSocketFrame()); return true; } handler.open(hs, ctx); ctx.pipeline().removeLast(); ctx.pipeline().addLast(new WebSocketServerHandler(handler, hs, session)); hs.handshake(ctx.channel(), request); return true; } }