package cn.xpleaf.protostuff.netty.echoservice;
import java.util.UUID;
import cn.xpleaf.protostuff.netty.pojo.EchoRequest;
import cn.xpleaf.protostuff.netty.pojo.EchoResponse;
import cn.xpleaf.protostuff.netty.pojo.User;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 接收到的对象的类型为EchoRequest
EchoRequest req = (EchoRequest) msg;
System.out.println(req.getRequestId() + " : " + req.getRequestObj());
// 创建需要传输的user对象
User user = new User();
user.setName("server");
user.setAge(10);
// 创建传输的user对象载体EchoRequest对象
EchoResponse resp = new EchoResponse();
// 设置responseId
resp.setResponseId(UUID.randomUUID().toString());
// 设置需要传输的对象
resp.setResponseObj(user);
// 设置需要传输的对象的类型
resp.setResponseObjClass(resp.getResponseObj().getClass());
// 调用writeAndFlush将数据发送到socketChannel
ctx.writeAndFlush(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}package cn.xpleaf.protostuff.netty.echoservice;
import cn.xpleaf.protostuff.netty.pojo.EchoResponse;
import cn.xpleaf.protostuff.netty.utils.EchoDecoder;
import cn.xpleaf.protostuff.netty.utils.EchoEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class EchoClient {
public void connect(int port, String host) throws Exception {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
// 设置TCP连接超时时间
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// 添加
ch.pipeline().addLast(new EchoDecoder(EchoResponse.class));
// 添加编码器
ch.pipeline().addLast(new EchoEncoder());
// 添加业务处理handler
ch.pipeline().addLast(new EchoClientHandler());
}
});
// 发起异步连接操作(注意服务端是bind,客户端则需要connect)
ChannelFuture f = b.connect(host, port).sync();
// 等待客户端链路关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放NIO线程组
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if(args != null && args.length > 0) {
try {
port = Integer.valueOf(port);
} catch (NumberFormatException e) {
// 采用默认值
}
}
new EchoClient().connect(port, "localhost");
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-83177-4.html
此人完了