Netty 客户端与服务端通信 demo

服务端代码
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
*
* Title: NettyServer
* Description: Netty服务端
* Version:1.0.0
* @author Administrator
* @date 2017-8-31
*/
public class NettyServer {
private static final int port = 6789; //设置服务端端口
private static EventLoopGroup group = new NioEventLoopGroup(); // 通过nio方式来接收连接和处理连接
private static ServerBootstrap b = new ServerBootstrap();

    /**
     * Netty创建全部都是实现自AbstractBootstrap。
     * 客户端的是Bootstrap,服务端的则是    ServerBootstrap。
     **/
    public static void main(String[] args) throws InterruptedException {
        try {
            b.group(group);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new NettyServerFilter()); //设置过滤器
            // 服务器绑定端口监听
            ChannelFuture f = b.bind(port).sync();
            System.out.println("服务端启动成功...");
            // 监听服务器关闭监听
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully(); 关闭EventLoopGroup,释放掉所有资源包括创建的线程  
        }
    }

}

服务端业务逻辑
import java.net.InetAddress;
import java.util.Date;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
*
* Title: HelloServerHandler
* Description: 服务端业务逻辑
* Version:1.0.0
* @author Administrator
* @date 2017-8-31
*/
public class NettyServerHandler extends SimpleChannelInboundHandler {
/*
* 收到消息时,返回信息
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg)
throws Exception {
// 收到消息直接打印输出
System.out.println(“服务端接受的消息 : ” + msg);
if(“quit”.equals(msg)){//服务端断开的条件
ctx.close();
}
Date date=new Date();
// 返回客户端消息
ctx.writeAndFlush(date+”\n”);
}

/*
 * 建立连接时,返回消息
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress());
    ctx.writeAndFlush("客户端"+ InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接! \n");
    super.channelActive(ctx);
}

}

服务端过滤器
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
*
* Title: HelloServerInitializer
* Description: Netty 服务端过滤器
* Version:1.0.0
* @author Administrator
* @date 2017-8-31
*/
public class NettyServerFilter extends ChannelInitializer {

 @Override
 protected void initChannel(SocketChannel ch) throws Exception {
     ChannelPipeline ph = ch.pipeline();
     // 以("\n")为结尾分割的 解码器
     ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
     // 解码和编码,应和客户端一致
     ph.addLast("decoder", new StringDecoder());
     ph.addLast("encoder", new StringEncoder());
     ph.addLast("handler", new NettyServerHandler());// 服务端业务逻辑
 }

}

客户端
客户端的主要工作是
1,连接到服务端
2,向服务端发送数据数据
3,处理服务端返回的数据
4,关闭连接
而且客户端相关代码也和服务端类似。

客户端
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.IOException;
/**
*
* Title: NettyClient
* Description: Netty客户端
* Version:1.0.0
* @author Administrator
* @date 2017-8-31
*/
public class NettyClient {

public static String host = "127.0.0.1";  //ip地址
public static int port = 6789;          //端口
/// 通过nio方式来接收连接和处理连接   
private static EventLoopGroup group = new NioEventLoopGroup(); 
private static  Bootstrap b = new Bootstrap();
private static Channel ch;

/**
 * Netty创建全部都是实现自AbstractBootstrap。
 * 客户端的是Bootstrap,服务端的则是    ServerBootstrap。
 **/
public static void main(String[] args) throws InterruptedException, IOException { 
        System.out.println("客户端成功启动...");
        b.group(group);
        b.channel(NioSocketChannel.class);
        b.handler(new NettyClientFilter());
        // 连接服务端
        ch = b.connect(host, port).sync().channel();
        star();
}

public static void star() throws IOException{
    String str="Hello Netty";
    ch.writeAndFlush(str+ "\r\n");
    System.out.println("客户端发送数据:"+str);

}

}

客户端业务逻辑实现
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
*
* Title: NettyClientHandler
* Description: 客户端业务逻辑实现
* Version:1.0.0
* @author Administrator
* @date 2017-8-31
*/
public class NettyClientHandler extends SimpleChannelInboundHandler {

@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {  
    System.out.println("客户端接受的消息: " + msg);
}

//
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("正在连接... ");
    super.channelActive(ctx);
}

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("连接关闭! ");
    super.channelInactive(ctx);
}

}

客户端过滤器
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
*
* Title: NettyClientFilter
* Description: Netty客户端 过滤器
* Version:1.0.0
* @author Administrator
* @date 2017-8-31
*/
public class NettyClientFilter extends ChannelInitializer {

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline ph = ch.pipeline();
    /*
     * 解码和编码,应和服务端一致
     * */
    ph.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    ph.addLast("decoder", new StringDecoder());
    ph.addLast("encoder", new StringEncoder());
    ph.addLast("handler", new NettyClientHandler()); //客户端的逻辑
}

}

图片效果图:
这里写图片描述

这里写图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值