RPC服务端+客户端 参考代码

1 篇文章 0 订阅

服务端启动类

package com.netty.demo.server;

 

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.Channel;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.nio.NioServerSocketChannel;

 

/**

 * • 配置服务器功能,如线程、端口 • 实现服务器处理程序,它包含业务逻辑,决定当有一个请求连接或接收数据时该做什么

 *

 * @author wilson

 *

 */

public class EchoServer {

 

private final int port;

 

public EchoServer(int port) {

this.port = port;

}

 

public void start() throws Exception {

EventLoopGroup eventLoopGroup = null;

try {

//创建ServerBootstrap实例来引导绑定和启动服务器

ServerBootstrap serverBootstrap = new ServerBootstrap();

//创建NioEventLoopGroup对象来处理事件,如接受新连接、接收数据、写数据等等

eventLoopGroup = new NioEventLoopGroup();

//指定通道类型为NioServerSocketChannel,设置InetSocketAddress让服务器监听某个端口已等待客户端连接。

serverBootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class).localAddress("localhost",port).childHandler(new ChannelInitializer<Channel>() {

//设置childHandler执行所有的连接请求

@Override

protected void initChannel(Channel ch) throws Exception {

ch.pipeline().addLast(new EchoServerHandler());

}

});

// 最后绑定服务器等待直到绑定完成,调用sync()方法会阻塞直到服务器完成绑定,然后服务器等待通道关闭,因为使用sync(),所以关闭操作也会被阻塞。

ChannelFuture channelFuture = serverBootstrap.bind().sync();

System.out.println("开始监听,端口为:" + channelFuture.channel().localAddress());

channelFuture.channel().closeFuture().sync();

} finally {

eventLoopGroup.shutdownGracefully().sync();

}

}

 

public static void main(String[] args) throws Exception {

new EchoServer(20000).start();

}

package com.netty.demo.server;

 

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelFutureListener;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.ChannelInboundHandlerAdapter;

 

import java.util.Date;

 

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

 

@Override

public void channelRead(ChannelHandlerContext ctx, Object msg)

throws Exception {

System.out.println("server 读取数据……");

//读取数据

        ByteBuf buf = (ByteBuf) msg;

        byte[] req = new byte[buf.readableBytes()];

        buf.readBytes(req);

        String body = new String(req, "UTF-8");

        System.out.println("接收客户端数据:" + body);

        //向客户端写数据

        System.out.println("serverclient发送数据");

        String currentTime = new Date(System.currentTimeMillis()).toString();

        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());

        ctx.write(resp);

}

 

@Override

public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

System.out.println("server 读取数据完毕..");

        ctx.flush();//刷新后才将数据发出到SocketChannel

}

 

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)

throws Exception {

cause.printStackTrace();

ctx.close();

}

 

}


}

客户端

package com.netty.demo.client;

 

import io.netty.bootstrap.Bootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.EventLoopGroup;

import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;

 

import java.net.InetSocketAddress;

 

/**

 * • 连接服务器 • 写数据到服务器 • 等待接受服务器返回相同的数据 • 关闭连接

 *

 * @author wilson

 *

 */

public class EchoClient {

 

private final String host;

private final int port;

 

public EchoClient(String host, int port) {

this.host = host;

this.port = port;

}

 

public void start() throws Exception {

EventLoopGroup nioEventLoopGroup = null;

try {

//创建Bootstrap对象用来引导启动客户端

Bootstrap bootstrap = new Bootstrap();

//创建EventLoopGroup对象并设置到Bootstrap中,EventLoopGroup可以理解为是一个线程池,这个线程池用来处理连接、接受数据、发送数据

nioEventLoopGroup = new NioEventLoopGroup();

//创建InetSocketAddress并设置到Bootstrap中,InetSocketAddress是指定连接的服务器地址

bootstrap.group(nioEventLoopGroup).channel(NioSocketChannel.class).remoteAddress(new InetSocketAddress(host, port))

.handler(new ChannelInitializer<SocketChannel>() {

//添加一个ChannelHandler,客户端成功连接服务器后就会被执行

@Override

protected void initChannel(SocketChannel ch)

throws Exception {

ch.pipeline().addLast(new EchoClientHandler());

}

});

// • 调用Bootstrap.connect()来连接服务器

ChannelFuture f = bootstrap.connect().sync();

// • 最后关闭EventLoopGroup来释放资源

f.channel().closeFuture().sync();

} finally {

nioEventLoopGroup.shutdownGracefully().sync();

}

}

 

public static void main(String[] args) throws Exception {

new EchoClient("localhost", 20000).start();

}

}

package com.netty.demo.client;

 

import io.netty.buffer.ByteBuf;

import io.netty.buffer.ByteBufUtil;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;

  

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {  

      //客户端连接服务器后被调用

    @Override  

    public void channelActive(ChannelHandlerContext ctx) throws Exception {  

     System.out.println("客户端连接服务器,开始发送数据……");

     byte[] req = "QUERY TIME ORDER".getBytes();

     ByteBuf  firstMessage = Unpooled.buffer(req.length);

        firstMessage.writeBytes(req);

        ctx.writeAndFlush(firstMessage);  

    }  

  // 从服务器接收到数据后调用

    @Override  

    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {  

      System.out.println("client 读取server数据..");

         //服务端返回消息后

         ByteBuf buf = (ByteBuf) msg;

         byte[] req = new byte[buf.readableBytes()];

         buf.readBytes(req);

         String body = new String(req, "UTF-8");

         System.out.println("服务端数据为 :" + body);

}  

  // 发生异常时被调用

    @Override  

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  

      System.out.println("client exceptionCaught..");

         // 释放资源

         ctx.close();

    }  

}  

注:如有不明白的地方,可私信我




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值