Example usage for io.netty.handler.codec.http.websocketx TextWebSocketFrame TextWebSocketFrame

List of usage examples for io.netty.handler.codec.http.websocketx TextWebSocketFrame TextWebSocketFrame

Introduction

In this page you can find the example usage for io.netty.handler.codec.http.websocketx TextWebSocketFrame TextWebSocketFrame.

Prototype

public TextWebSocketFrame(ByteBuf binaryData) 

Source Link

Document

Creates a new text frame with the specified binary data.

Usage

From source file:WebSocketFrameHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {

    if (frame instanceof TextWebSocketFrame) {
        String inboundMessage = ((TextWebSocketFrame) frame).text();
        Timestamp currentTimestamp = new java.sql.Timestamp(Calendar.getInstance().getTime().getTime());

        //Message to be sent.
        String Echo = "Timestamp: " + currentTimestamp + " " + ctx.channel().toString() + "\n" + "Server tag: "
                + tag + "Server tag: " + tag + " -- Text: " + inboundMessage;

        System.out.println(Echo); //same message to server's out
        ctx.channel().writeAndFlush(new TextWebSocketFrame(Echo));

    } else {//from www. j a v a 2  s. c o m
        String message = "Unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }

}

From source file:adalightserver.http.HttpServer.java

License:Apache License

private TextWebSocketFrame makeWebSocketEventFrame(String eventName, String data) {
    StringBuilder b = new StringBuilder();
    b.append("{\"type\":\"ev\", \"name\":\"").append(eventName).append("\", \"data\":").append(data)
            .append("}");
    return new TextWebSocketFrame(b.toString());
}

From source file:adalightserver.http.HttpServer.java

License:Apache License

private TextWebSocketFrame makeWebSocketResultMsg(long id, Object result, Object error) {
    JsonBuilder builder = new JsonBuilder();
    Map<String, Object> msg = new HashMap<String, Object>();
    msg.put("type", "rp");
    msg.put("id", id);
    if (error != null) {
        msg.put("error", error);
    } else {/*from  w  w  w . j av a2s  .c o m*/
        msg.put("result", result);
    }
    builder.call(msg);
    return new TextWebSocketFrame(builder.toString());
}

From source file:app.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        channels.remove(ctx.channel());// w  w  w  . j  av  a  2 s .  co  m
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (frame instanceof TextWebSocketFrame) {
        JSONObject msg = (JSONObject) JSONValue.parse(((TextWebSocketFrame) frame).text());

        if (msg == null) {
            System.out.println("Unknown message type");
            return;
        }

        switch (msg.get("type").toString()) {
        case "broadcast":
            final TextWebSocketFrame outbound = new TextWebSocketFrame(msg.toJSONString());
            channels.forEach(gc -> gc.writeAndFlush(outbound.duplicate().retain()));
            msg.replace("type", "broadcastResult");
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        case "echo":
            ctx.writeAndFlush(new TextWebSocketFrame(msg.toJSONString()));
            break;
        default:
            System.out.println("Unknown message type");
        }

        return;
    }
}

From source file:be.yildizgames.module.network.netty.client.WebSocketClientNetty.java

License:MIT License

@Override
protected TextWebSocketFrame buildMessage(String message) {
    return new TextWebSocketFrame(message);
}

From source file:be.yildizgames.module.network.netty.server.WebSocketNettySession.java

License:MIT License

@Override
protected void write(Channel ch, String message) {
    ch.writeAndFlush(new TextWebSocketFrame(message));
}

From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // ?//from   w  ww .  j ava 2  s  .  co  m
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;
    }
    // ?Ping?
    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()));
    }

    // ?
    String request = ((TextWebSocketFrame) frame).text();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(String.format("%s received %s", ctx.channel(), request));
    }
    ctx.channel().write(new TextWebSocketFrame(request
            + " , Netty WebSocket?" + new java.util.Date().toString()));
}

From source file:ca.lambtoncollege.netty.webSocket.ClientWebSocket.java

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from   w ww  .  ja v  a  2s. c  o  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final ClientHandlerWebSocket handler = new ClientHandlerWebSocket(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/*from   w w w  . jav a  2 s.  co m*/
    }
    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()));
    }

    // Send the uppercase string back.
    String request = ((TextWebSocketFrame) frame).text();
    System.err.printf("%s received %s%n", ctx.channel(), request);
    ctx.channel().write(new TextWebSocketFrame(request.toUpperCase()));
}

From source file:catacumba.websocket.internal.DefaultWebSocket.java

License:Apache License

@Override
public CompletionStage<Void> send(String text) {
    final CompletableFuture<Void> f = new CompletableFuture<Void>();
    channel.writeAndFlush(new TextWebSocketFrame(text)).addListener(future -> {
        if (future.isSuccess()) {
            f.complete(null);// w  ww  .  ja  v  a2s  .c om
        } else {
            f.completeExceptionally(future.cause());
        }
    });

    return f;
}