1.目标
解码服务器消息中的[消息有效内容],有效内容首尾是固定的分隔符$OUTSTA
和#
,内容格式如下:
$OUTSTA[消息有效内容]#[结束内容,可能为有效内容]
2.pom.xml
添加netty依赖
io.netty
netty-all
4.1.14.Final
3.TcpClient.java
package com.airkisser.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
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.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* TCP/IP客户端
*/
public class TcpClient {
/**
* 连接TCP服务端
* @param host 服务端IP
* @param port 服务端监听端口号
*/
public void connect(String host, int port) {
// 配置NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new LoggingHandler(LogLevel.DEBUG))
.handler(new ChannelInitializer() {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ByteBuf startDelimiter = Unpooled.copiedBuffer("$OUTSTA".getBytes());
ByteBuf endDelimiter = Unpooled.copiedBuffer("#".getBytes());
socketChannel.pipeline()
/* 分隔符解码器
如果接收内容超过2048的长度还没有查找到分隔符,抛出TooLongFrameException异常,防止内存溢出
可以定义一个或多个分隔符,解码器将只取分隔符之间的内容
例如:
服务端一次返回消息内容为:
$OUTSTA65535,10,1256,170823_162540,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0#ss
则定义两个分隔符"$OUTSTA"和"#ss"
那么第一次接收服务器返回消息时解码后内容为一条:
65535,10,1256,170823_162540,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0
还剩下'#ss'后面的内容没有被解码,等待接收下一条服务器消息
第二次接收服务器返回消息时解码后的内容为两条:
第一条:空字符串""
第二条:
65535,10,1256,170823_162540,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0
需要注意的是:"#ss"和"$OUTSTA"作为分隔的首尾,中间的内容被解码为空字符串
需要对解码后的内容进行空字符串过滤
如果定义两个分隔符为"$OUTSTA"和"#"
那么第一次接收服务器返回消息时解码后内容为一条:
65535,10,1256,170823_162540,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0
还剩下'#'后面的内容没有被解码,等待接收下一条服务器消息
第二次接收服务器返回消息时解码后的内容为两条:
第一条:ss
第二条:
65535,10,1256,170823_162540,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0
其中第一条'ss'是第一次接收到的服务器消息'#'后面的内容以及第二次接收到的服务器消息'$OUTSTA'之前的内容
是我们不需要的内容,可以通过限定长度过滤掉,不对该条消息做处理
同理,还剩下'#'后面的内容没有被解码,等待接收下一条服务器消息
*/
.addLast(new DelimiterBasedFrameDecoder(2048, startDelimiter, endDelimiter))
/*
* 将分隔符解码后的内容转为字符串
*/
.addLast(new StringDecoder())
.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//@TODO 进行连接成功后的操作
System.out.println("连接成功... ");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// StringDecoder解码后的信息,
String message = (String) msg;
// 前面已经说了,通过分隔符解码后的消息中有一部分并不是我们需要的消息
// 此时我们可以通过一些限制条件过滤掉这些我们不需要的内容,比如空字符串,此处通过限定长度来过滤:长度大于10,
// 可以根据实际情况进行过滤
// 只对过滤后的内容进行解析
if (message != null && message.length() > 10) {
System.out.println("接收内容:\n" + message);
// @TODO 对消息进行解析等操作,一般放在线程或线程池中处理
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// @TODO 捕捉到异常后进行重连或者其他异常处理操作
System.out.println("发生异常...");
cause.printStackTrace();
ctx.channel().close();
}
});
}
});
try {
ChannelFuture f = b.connect(host, port).sync();
} catch (InterruptedException e) {
// @TODO 处理连接失败后的异常
e.printStackTrace();
}
}
public static void main(String[] args) {
TcpClient client = new TcpClient();
client.connect("127.0.0.1", 12800);
}
}
4.测试
步骤1:启动TCP模拟服务端
监听地址:127.0.0.1
监听端口:12800
模拟消息:
$OUTSTA65535,10,1256,170823_162540,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0,0,0#ss
客户端需要的有效内容:
65535,10,1256,170823_162540,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0.0,0,0,0,0
步骤2:运行TcpClient中的main方法作为客户端
步骤3:服务端发送消息给客户端,客户端控制台打印内容如下:
解码完成。