入门demo

一:maven依赖

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

二:server

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder()).addLast(new StringEncoder()) 
                        .addLast(new SimpleChannelInboundHandler<String>() {
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                Channel c= ctx.channel();
                                System.out.println("server log"+msg);
                                c.writeAndFlush(" server 反馈 "+msg);
                            }
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                System.out.println("server log 建立了一个连接");
                                super.channelActive(ctx);
                            }
                            
                        });
                    }
                })
                .bind(8000); 
        System.out.println("server start");
    }
}

三:client

import java.util.Date;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyClient {
    
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
    
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new StringDecoder()).addLast(new StringEncoder()) .addLast(new SimpleChannelInboundHandler<String>(){
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                System.out.println("client log"+msg);                           
                            }
                        });
                    }
                });
        Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();
        while (true) {
            channel.writeAndFlush(new Date() + ": hello world!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } 
    }
}

介绍。

以上就是client发送消息给server,然后server拿到消息。


对于server来说,因为客户端有很多,他是如何区分谁是谁的呢?以上如server中的protected void channelRead0(ChannelHandlerContext ctx, String msg),对于server来说可以从ctx中拿到Channel,这个时候,可以从msg中拿到1个id,然后用Map把这个id和Channel缓存起来,这样就可以知道谁是谁了。以此,server主动去发消息给client也是完全可以的。


client发消息给server,他如何接受消息呢。对于client来说发送消息的msg可以放一个uuid,这个uuid表示本次请求。server拿到uuid后,处理完逻辑原封不动返回,如此,从client根本这个uuid便知道请求来自哪里。


对于client来说,一个Channel便是和server通话的一个管道,你可以理解为1部手机。


当客户端请求server的时候,客户端会有一个Channel,Server会有一个对应的Channel,如果client挂了后,server的Channel还在,需要手动fireChannelActive,如果server没有断掉的机子,client不断去连然后挂掉。这个时候,server的线程会越来越多越来越多。所以server要调用ChannelHandlerContext||ctx.fireChannelActive();才行。ChannelHandlerContext和Channel也是一一对应的。

注意

很多在网上的例子会这么来写server端代码

 ChannelFuture f = b.bind().sync(); 
f.channel().closeFuture().sync();
// bind() 和 bind(8080) 如果在上面的代码里有调用.localAddress(new InetSocketAddress(port))则这里可以不写端口。
// bind后调用sync。注意这里bind后返回的是ChannelFuture指的是对bind行为的Future,然后sync()就表示直到bind完成后线程继续往下走。
// f.channel().closeFuture().sync(); 先从 ChannelFuture f 中获取Channel对象,然后获取他的closeFuture对象,然后调用sync(),意思是当该Channel关闭的时候,线程继续往下走。

这里还需要结合dubbo,rocketmq来看启动的问题,未完待续。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 待完善 Channel、EventLoop和ChannelFuture Channel、EventLoop和Cha...
    codersm阅读 4,125评论 0 0
  • 服务端目录结构 api maven dubbo-server <groupId>com.sjx.dubbo</g...
    xuan2017阅读 1,677评论 0 0
  • Dubbo是阿里开源的分布式RPC通信框架,目前在国内使用范围比较广,本文详细描述Dubbo的入门级使用过程,希望...
    小明同学的学长阅读 10,473评论 0 7
  • Dubbo是阿里巴巴公司开源的一个高性能优秀的服务框架,使得应用可通过高性能的 RPC 实现服务的输出和输入功能,...
    DrinkwaterGor阅读 2,586评论 0 1
  • 一丶什么是Spring Boot Spring 诞生时是 Java 企业版(Java Enterprise Edi...
    Cehae阅读 3,720评论 0 3