服务端 代码
package sample.appfunction.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import java.io.IOException;
public class nettyServerQA {
public int currentValue=0;
public String pubMSG;
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new NettyServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
// Bind and start to accept incoming connections.
ChannelFuture f = b.bind(1003).sync(); // (7)
// Wait until the server socket is closed.
// In this example, this does not happen, but you can do that to gracefully
// shut down your server.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
@ChannelHandler.Sharable
public class NettyServerHandler extends ChannelInboundHandlerAdapter { // (1)
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws IOException { // (2)
String byteBuf = (String) msg;
pubMSG=byteBuf;
// System.out.println("客户端发来的消息是:" + byteBuf);
System.out.println("收到连接的原信息 "+pubMSG);
if(byteBuf.contains("write:")){
currentValue=Integer.parseInt(byteBuf.split(":")[1]);
System.out.println("收到写入请求 "+currentValue);
}
if(byteBuf.contains("read")){
ctx.writeAndFlush(Unpooled.copiedBuffer(currentValue+"\r\n", CharsetUtil.UTF_8));
System.out.println("收到读取请求 "+currentValue);
}
}
//数据读取完毕事件
public void channelReadComplete(ChannelHandlerContext ctx) throws IOException, InterruptedException {
//数据读取完毕,将信息包装成一个Buffer传递给下一个Handler,Unpooled.copiedBuffer会返回一个Buffer
//调用的是事件处理器的上下文对象的writeAndFlush方法
//意思就是说将 你好 传递给了下一个handler
// ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已经读取消息完成!"+pubMSG+"\r\n", CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
// Close the connection when an exception is raised.
cause.printStackTrace();
Channel channel = ctx.channel();
if(channel.isActive())ctx.close();
}
}
public static void main(String[] args) {
try {
new nettyServerQA().run();
} catch (Exception e) {
e.printStackTrace();
System.out.println("server netty exception");
}
}
}
客户端handler代码
package sample.appfunction.netty;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import java.io.IOException;
//客户端业务处理类
public class NettyClientHandlerInner extends ChannelInboundHandlerAdapter {
ChannelHandlerContext ctxOut;
String RESPSTR;
//通道就绪事件(就是在bootstrap启动助手配置中addlast了handler之后就会触发此事件)
//但我觉得也可能是当有客户端连接上后才为一次通道就绪
public void channelActive(ChannelHandlerContext ctx) throws IOException, InterruptedException {
System.out.println("1 客户端消息,通道激活,可以发送消息了");
ctx.writeAndFlush(Unpooled.copiedBuffer("read"+"\r\n", CharsetUtil.UTF_8));
ctxOut=ctx;
System.out.println(ctxOut.toString());
}
//数据读取事件
public void channelRead(ChannelHandlerContext ctx, Object msg) {
//传来的消息包装成字节缓冲区
String byteBuf = (String) msg;
// ByteBuf byteBuf = (ByteBuf) msg;
//Netty提供了字节缓冲区的toString方法,并且可以设置参数为编码格式:CharsetUtil.UTF_8
System.out.println("2 客户端读取服务返回的数据:" + byteBuf+" and ctx is "+ctx.toString());
RESPSTR=byteBuf;
ctxOut=ctx;
}
public void sendMSG(String msg){
System.out.println("3 send command is "+msg);
if(ctxOut!=null){
ctxOut.writeAndFlush(Unpooled.copiedBuffer(msg+"\r\n", CharsetUtil.UTF_8));
}else{
System.out.println("but found ctxOut exception is "+ctxOut);
}
}
public String getMSG(){
sendMSG("read");
return RESPSTR;
}
}
客户端代码
package sample.appfunction.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class nettyClientQA {
public void connectToServer(NettyClientHandlerInner nettyClientHandler){
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.option(ChannelOption.SO_KEEPALIVE, true); // (4)
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(nettyClientHandler);
ch.pipeline().addLast(new ExceptionHandlingChannelHandler());
}
});
// Start the client.
ChannelFuture f = b.connect("127.0.0.1", 1003).sync(); // (5)
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
// 连接成功,无需重连
System.out.println("connect to server success");
} else {
// 连接失败,进行重连
System.out.println("connect to server failed,try it again");
future.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
b.connect(); // 重新连接服务端
}
}, 1, TimeUnit.SECONDS); // 1秒后进行重连
}
}
});
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
}
}
public class ExceptionHandlingChannelHandler extends ChannelInboundHandlerAdapter {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace(); // 打印异常堆栈跟踪
System.out.println("发生异常");
}
}
public static void main(String[] args) {
NettyClientHandlerInner nettyClientQA=new NettyClientHandlerInner();
nettyClientQA nettyClientQA1=new nettyClientQA();
nettyClientQA.sendMSG("write:1");
nettyClientQA1.connectToServer(nettyClientQA);
}
}
背景是:在连接上服务端的时候要写一个消息,让服务端某个变量值为1
问题是:但是运行代码报错but found ctxOut exception is null?
解决办法:
首先,main方法中这样写是不行的,因为程序不能运行到sendMSG哪里
public static void main(String[] args) {
NettyClientHandlerInner nettyClientQA=new NettyClientHandlerInner();
nettyClientQA nettyClientQA1=new nettyClientQA();
nettyClientQA1.connectToServer(nettyClientQA);
nettyClientQA.sendMSG("write:1");
}
其次,ctx为null,意味着还没有初始化这个channel,因此我们尝试在加上一个等待时间如下就可以了,问题解决
public static void main(String[] args) {
NettyClientHandlerInner nettyClientHandlerInner=new NettyClientHandlerInner();
nettyClientQA nettyClientQA1=new nettyClientQA();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
nettyClientHandlerInner.sendMSG("write:0");
}
}).start();
nettyClientQA1.connectToServer(nettyClientHandlerInner);
}```