收到任务要调试板子,需要给板子发送16进制字符串指令,然后板子回馈给我指令,但是我怎么连接板子呢,最开始采用Socket方式,我需要的场景是我发送指令板子就会给我回馈信息,我才能知道我的这次指令是成功还是失败!但是Socket对这种方式感觉不太友好,想要一直接收信息就需要循环,后来辗转反侧使用了netty,感觉很好用,下面就贴出使用代码
1.添加初始化管道
package com.hs.server.tcpDemo.netty;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
/**
* @ClassName : ChannelInitializer
* @Description :
* @Author : df
* @Date: 2021-01-13 09:31
*/
public class ChannelInit extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel channel) {
// 基于换行符号
/*channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
// 解码转String,注意调整自己的编码格式GBK、UTF-8
channel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));
// 解码转String,注意调整自己的编码格式GBK、UTF-8
channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));*/
//channel.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));
// 在管道中添加我们自己的接收数据实现方法
channel.pipeline().addLast(new ServerHandler());
}
}
2.客户端连接,以及接收客户端的信息
package com.hs.server.tcpDemo.netty;
import cn.hutool.json.JSONObject;
import com.hs.server.enums.CommunicationEnum;
import com.hs.server.mapper.HexLabelMapper;
import com.hs.server.service.TcpPlcHelper;
import com.hs.server.utils.ByteUtils;
import com.hs.server.utils.RedisCache;
import com.hs.server.utils.spring.SpringContextUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ClassName : ServerHandler
* @Description :
* @Author : df
* @Date: 2021-01-13 09:34
*/
public class ServerHandler extends ChannelInboundHandlerAdapter {
private Logger logger = LoggerFactory.getLogger(ServerHandler.class);
/**
* 当客户端主动链接服务端的链接后,这个通道就是活跃的了。也就是客户端与服务端建立了通信通道并且可以传输数据
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
SocketChannel channel = (SocketChannel) ctx.channel();
logger.info("客户端连接上服务端");
channel.re

最低0.47元/天 解锁文章
343

被折叠的 条评论
为什么被折叠?



