Netty應(yīng)答服務(wù)

需求:服務(wù)端接收客戶端發(fā)送的數(shù)據(jù)葵蒂,并將數(shù)據(jù)返回給客戶端

  • 客戶端代碼

public final class EchoClient {

    public static void main(String[] args) {
        try {
            NioEventLoopGroup group = new NioEventLoopGroup();
            Channel channel = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            //添加handler
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new StringEncoder()); //bytebuf轉(zhuǎn)為字符串
                            ch.pipeline().addLast(new StringDecoder()); //bytebuf轉(zhuǎn)為字符串
                            ch.pipeline().addLast(new EchoClientHandler()); //bytebuf轉(zhuǎn)為字符串

                        }
                    }).connect(new InetSocketAddress("localhost", 8007))
                    .sync()
                    .channel();
            new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String line = scanner.nextLine();
                    if ("q".equals(line)) {
                        channel.close();
                        // log.debug("處理關(guān)閉之后操作");
                        break;
                    }
                    channel.writeAndFlush(line);
                }
            }, "input_client").start();

            //  方法①獲取closeFuture對(duì)象
           /* ChannelFuture closeFuture = channel.closeFuture();
            log.debug("waiting close");
            closeFuture.sync();
            log.debug("處理關(guān)閉之后操作");*/

            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.addListener((ChannelFutureListener) future -> {
                group.shutdownGracefully();//線程組停下來(lái)
            });

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

  • 客戶端handler
/*
 * 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:
 *
 *   https://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 io.netty.example.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * Handler implementation for the echo client.  It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    private  ByteBuf firstMessage;

    /**
     * Creates a client-side handler.
     */
    public EchoClientHandler() {
      /*  firstMessage = Unpooled.buffer(EchoClient.SIZE);
        for (int i = 0; i < firstMessage.capacity(); i ++) {
            firstMessage.writeByte((byte) i);
        }*/
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
       // ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("接受服務(wù)器的消息:"+msg);
    }


    @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();
    }
}

  • 服務(wù)端代碼


public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        final EchoServerHandler serverHandler = new EchoServerHandler();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 100)
             .handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     p.addLast(new LoggingHandler(LogLevel.DEBUG));

                     if (sslCtx != null) {
                         p.addLast(sslCtx.newHandler(ch.alloc()));

                     }
                     p.addLast(new StringEncoder()); //bytebuf轉(zhuǎn)為字符串
                     p.addLast(new StringDecoder()); //bytebuf轉(zhuǎn)為字符串
                     p.addLast(serverHandler);
                 }
             });

            // Start the server.
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

  • 服務(wù)端handler
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // ctx.write(msg);
        System.out.println("接受客戶端的消息:" + msg);

        ctx.writeAndFlush(msg.toString().toUpperCase());
    }

    @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();
    }
}

客戶端
服務(wù)端
參考

netty寫個(gè)應(yīng)答服務(wù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末户辫,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異筷弦,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)抑诸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門烂琴,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人蜕乡,你說(shuō)我怎么就攤上這事奸绷。” “怎么了层玲?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵号醉,是天一觀的道長(zhǎng)反症。 經(jīng)常有香客問(wèn)我,道長(zhǎng)畔派,這世上最難降的妖魔是什么铅碍? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮线椰,結(jié)果婚禮上胞谈,老公的妹妹穿的比我還像新娘。我一直安慰自己憨愉,他們只是感情好烦绳,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著莱衩,像睡著了一般爵嗅。 火紅的嫁衣襯著肌膚如雪娇澎。 梳的紋絲不亂的頭發(fā)上笨蚁,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音趟庄,去河邊找鬼括细。 笑死,一個(gè)胖子當(dāng)著我的面吹牛戚啥,可吹牛的內(nèi)容都是我干的奋单。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼猫十,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼览濒!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起拖云,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤贷笛,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后宙项,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體乏苦,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年尤筐,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了汇荐。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡盆繁,死狀恐怖掀淘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情油昂,我是刑警寧澤繁疤,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布咖为,位于F島的核電站,受9級(jí)特大地震影響稠腊,放射性物質(zhì)發(fā)生泄漏躁染。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一架忌、第九天 我趴在偏房一處隱蔽的房頂上張望吞彤。 院中可真熱鬧,春花似錦叹放、人聲如沸饰恕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)埋嵌。三九已至,卻和暖如春俱恶,著一層夾襖步出監(jiān)牢的瞬間雹嗦,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工合是, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留了罪,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓聪全,卻偏偏與公主長(zhǎng)得像泊藕,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子难礼,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容