Netty: Socket: 代码执行顺序问题
Client
FirstClient.java
package com.me.socket.client;
import com.me.dto.TransportObject;
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.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class FirstClient {
private final String host;
private final int port;
public FirstClientHandler cl=new FirstClientHandler();
public FirstClient() {
this(0);
}
public FirstClient(int port) {
this("localhost", port);
}
public FirstClient(String host, int port) {
this.host = host;
this.port = port;
}
public void connect(String msg) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group) // 注册线程池
.channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
.remoteAddress(new InetSocketAddress(this.host, this.port)) // 绑定连接端口和host信息
.handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("--------------------client: channel log begin--------------------");
System.out.println("正在连接中...");
ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
// ch.pipeline().addLast(new FirstClientHandler());
ch.pipeline().addLast(cl);
ch.pipeline().addLast(new ByteArrayEncoder());
ch.pipeline().addLast(new ChunkedWriteHandler());
}
});
// System.out.println("服务端连接成功..");
ChannelFuture cf = b.connect().sync(); // 异步连接服务器
System.out.println("服务端连接成功..."); // 连接完成
// channel = cf.channel();
cl.myctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); // 必须有flush
cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
System.out.println("连接已关闭.."); // 关闭完成
} finally {
group.shutdownGracefully().sync(); // 释放线程池资源
}
}
public static void main(String[] args) throws Exception {
TransportObject data = new TransportObject();
data.setId(999);
data.setName("xyz");
List<String> list = new ArrayList<String>();
list.add("111");
list.add("222");
list.add("333");
data.setList(list);
// 8882: second-server, transfer data to second-server
FirstClient firstClient = new FirstClient("127.0.0.1", 8882);
firstClient.connect(data.toString());
System.out.println("=========================");
}
}
FirstClientHandler.java
package com.me.socket.client;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.nio.charset.Charset;
public class FirstClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
public ChannelHandlerContext myctx;
/**
* 向服务端发送数据
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
myctx=ctx;
System.out.println("客户端与服务端通道-开启:" + ctx.channel().localAddress() + "channelActive");
// String sendInfo = "Hello 这里是first客户端 你好啊!";
// System.out.println("客户端准备发送的数据包:" + sendInfo);
// ctx.writeAndFlush(Unpooled.copiedBuffer(sendInfo, CharsetUtil.UTF_8)); // 必须有flush
}
/**
* channelInactive
*
* channel 通道 Inactive 不活跃的
*
* 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
*
*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("客户端与服务端通道-关闭:" + ctx.channel().localAddress() + "channelInactive");
System.out.println("--------------------client: channel log end--------------------");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
System.out.println("读取客户端通道信息..");
ByteBuf buf = msg.readBytes(msg.readableBytes());
System.out.println(
"客户端接收到的服务端信息:" + ByteBufUtil.hexDump(buf) + "; 数据包为:" + buf.toString(Charset.forName("utf-8")));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
System.out.println("异常退出:" + cause.getMessage());
}
}
Server
SecondServer.java
package com.me.socket.server;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.Charset;
public class SecondServer {
private final int port;
public SecondServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
sb.group(group, bossGroup) // 绑定线程池
.channel(NioServerSocketChannel.class) // 指定使用的channel
.localAddress(this.port)// 绑定监听端口
.childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
@Override
protected void initChannel(SocketChannel ch) throws Exception {
System.out.println("--------------------server: channel log begin--------------------");
System.out.println("报告");
System.out.println("信息:有一客户端链接到本服务端");
// System.out.println("IP:" + ch.localAddress().getHostName());
System.out.println("IP:" + ch.remoteAddress().getHostName());
// System.out.println("Port:" + ch.localAddress().getPort());
System.out.println("Port:" + ch.remoteAddress().getPort());
System.out.println("报告完毕");
ch.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));
ch.pipeline().addLast(new SecondServerHandler()); // 客户端触发操作
ch.pipeline().addLast(new ByteArrayEncoder());
}
});
ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
System.out.println(SecondServer.class + " 启动正在监听: " + cf.channel().localAddress());
cf.channel().closeFuture().sync(); // 关闭服务器通道
} finally {
group.shutdownGracefully().sync(); // 释放线程池资源
bossGroup.shutdownGracefully().sync();
}
}
public static void main(String[] args) throws Exception {
new SecondServer(8882).start(); // 启动
}
}
SecondServerHandler.java
package com.me.socket.server;
import com.me.dto.TransportObject;
import com.me.socket.client.SecondClient;
import com.google.gson.Gson;
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.io.UnsupportedEncodingException;
public class SecondServerHandler extends ChannelInboundHandlerAdapter {
private String rev;
/**
* channelAction
*
* channel 通道 action 活跃的
*
* 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
*
*/
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().localAddress().toString() + " 通道已激活!");
}
/**
* channelInactive
*
* channel 通道 Inactive 不活跃的
*
* 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
*
*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃!");
// 关闭流
System.out.println("--------------------server: channel log end--------------------");
}
/**
* TODO 此处用来处理收到的数据中含有中文的时 出现乱码的问题
* @param buf
* @return
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
/**
* 功能:读取first-server发送过来的信息
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 第一种:接收字符串时的处理
ByteBuf buf = (ByteBuf) msg;
// String rev = getMessage(buf);
rev = getMessage(buf);
System.out.println("second-server收到first-server发送的数据:" + rev);
}
/**
* 功能:读取完毕客户端发送过来的数据之后的操作
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("服务端接收数据完毕..");
// 第一种方法:写一个空的buf,并刷新写出区域。完成后关闭sock channel连接。
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
// 数据处理 Gson解析json
// TransportObject transportObject = new Gson().fromJson(rev, TransportObject.class);
// transportObject.getList().add("444");
// transportObject.setName("当前位置second");
// transportObject.setId(888);
// 数据传输 transfer data to 8883: third-server
// SecondClient secondClient = new SecondClient("127.0.0.1", 8883);
// data to send after operations
// secondClient.connect(transportObject.toString()+" | second msg");
// ctx.writeAndFlush(Unpooled.copiedBuffer("Success", CharsetUtil.UTF_8));
// ctx.flush();
// ctx.flush(); //
// 第二种方法:在client端关闭channel连接,这样的话,会触发两次channelReadComplete方法。
// ctx.flush().close().sync(); // 第三种:改成这种写法也可以,但是这中写法,没有第一种方法的好。
}
/**
* 功能:服务端发生异常的操作
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
System.out.println("异常信息:\r\n" + cause.getMessage());
}
}
代码执行顺序
FirstClient.java
cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
会 异步等待关闭连接channel
直到
SecondServerHandler.java
// 第一种方法:写一个空的buf,并刷新写出区域。完成后关闭sock channel连接。
// after this line finished, 'cf.channel().closeFuture().sync();' in FirstClient will be executed.
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
执行完毕