Netty服务端监听
package com.demo.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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.StringEncoder;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.PreDestroy;
@Slf4j
@Component
public class NettyServerListener {
private static int port = 8081;
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workGroup = new NioEventLoopGroup();
@PreDestroy
public void close() {
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
public void start() {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ServerHandler());
socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new ServerHandler());
}
});
try {
ChannelFuture future = serverBootstrap.bind(port).sync();
log.info("Netty通讯服务启动成功:{}",port);
future.channel().closeFuture().sync();
} catch (Exception e) {
log.warn("Netty通讯服务启动失败:{}" , port);
e.printStackTrace();
} finally {
try {
bossGroup.shutdownGracefully().sync();
workGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
接送端
package com.demo.netty;
import com.demo.service.DemoService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Autowired
private DemoService demoService;
public static Map list = new ConcurrentHashMap();
public static ServerHandler serverHandler;
public ServerHandler() {
}
@PostConstruct
public void init() {
serverHandler = this;
serverHandler.demoService = this.demoService;
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
String request = byteBuf.toString(CharsetUtil.UTF_8);
log.info("通讯连接:{}", request);
boolean containsCN = request.contains("CN=20");
if (containsCN) {
list.put(mac, (SocketChannel) channelHandlerContext.channel());
int code = -1;
String CN2 = request.split("CN=")[1].split(";", 0)[0];
if ("2011".equals(CN2)) {
code = serverHandler.demoService.insertData(request);
}
channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer("CN=" + CN2+";code=" + code, CharsetUtil.UTF_8));
}
}
public static String sendmsg(String mac,String data) {
if (StringUtils.isEmpty(list.get(mac))) {
return "通道不存在!";
}
Channel c = (Channel) list.get(mac);
log.info("sendmsg-getMac:{}", list.get(mac));
c.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
return returnText;
}
}
项目启动类添加netty服务器
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
SpringApplication springApplication = new SpringApplication(DemoApplication.class);
springApplication.run(args);
}
@Override
public void run(String... args) {
new NettyServerListener().start();
}