net.yuntutv.a8.ws.EchoServerHandler.java Source code

Java tutorial

Introduction

Here is the source code for net.yuntutv.a8.ws.EchoServerHandler.java

Source

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.yuntutv.a8.ws;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Handler implementation for the echo server.
 */
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    public static BlockingQueue<String> queue = new LinkedBlockingQueue<>();
    public static Channel c;
    static {
        Thread t = new Thread() {
            public void run() {
                while (true) {
                    try {
                        String s = queue.take();
                        c.write(s);
                    } catch (InterruptedException e) {

                    }
                }
            }
        };
        t.start();

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        c = ctx.channel();
        ByteBuf bb = (ByteBuf) msg;
        byte[] bs = new byte[bb.readableBytes()];
        bb.getBytes(0, bs);
        String s = new String(bs);
        s = s.replaceAll("\\s", "");
        System.out.println(s);
        ctx.write(s);
        //        try {
        //            queue.put(s);
        //        } catch (InterruptedException e) {
        //            e.printStackTrace();
        //        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}