博客
关于我
Netty4客户端入门代码示例
阅读量:336 次
发布时间:2019-03-04

本文共 1489 字,大约阅读时间需要 4 分钟。

添加Maven依赖:

        <dependency>            <groupId>io.netty</groupId>            <artifactId>netty-all</artifactId>            <version>4.1.36.Final</version>        </dependency>

示例代码:

import io.netty.bootstrap.Bootstrap;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioSocketChannel;public class NettyClient{    public static void main(String[] args)throws Exception    {        Bootstrap bootStrap = new Bootstrap();        NioEventLoopGroup workerGroup = new NioEventLoopGroup();        bootStrap.group(workerGroup)                .channel(NioSocketChannel.class)                .remoteAddress("127.0.0.1",8080)                .handler(new ChannelInitializer<Channel>()                {                    @Override                    protected void initChannel(Channel channel) throws Exception                    {                        channel.pipeline().addLast(new ClientHandler());                    }                });        ChannelFuture future = bootStrap.connect();        if (future.channel().isActive()){            future.channel().writeAndFlush("hello world");        }    }    static class ClientHandler extends ChannelInboundHandlerAdapter{        @Override        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception        {            System.out.println("read msg : "+msg);            ctx.writeAndFlush("Hello World");            super.channelRead(ctx, msg);        }    }}

转载地址:http://hume.baihongyu.com/

你可能感兴趣的文章
CI/CD and beyond with GitHub Actions
查看>>
回顾 | 如何快速开发一款扩展
查看>>
《进击吧!Blazor!》第一章 4.数据交互
查看>>
分享一个500异常
查看>>
怎么玩LOG4J
查看>>
Oracle创建用户,分配表空间
查看>>
自定义标签(JSP2.0)简单标签
查看>>
MyBatis自定义类型转换器
查看>>
SpringBoot缓存入门篇
查看>>
机器学习(湖北师范大学教程)-极大似然估计算法
查看>>
2019年下半年总结
查看>>
读《红楼梦》有感
查看>>
【数据库视频之数据库视图】
查看>>
【数据库视频之操作查询(一)】
查看>>
【C# 重构】—参数化查询, 需要参数,但未提供该参数
查看>>
决策树(二)—— ID3和C4.5
查看>>
leetcode做题记录0059
查看>>
leetcode做题记录0062
查看>>
Leetcode每日随机2021/4/26
查看>>
Leetcode每日随机2021/4/29
查看>>