由于工作需要,研究了SpringBoot搭建TCP通信的过程,对于工程需要的小伙伴,只是想快速搭建一个可用的服务.
其他的教程看了许多,感觉讲得太复杂,很容易弄乱,这里我只讲效率,展示快速搭建过程
TCPServer
由于TCP协议是Netty实现的,所以引入Netty的依赖
<dependency>
<groupId></groupId>
<artifactId>netty-all</artifactId>
<version>4.1.</version>
</dependency>
配置TCPServer
@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "")
public class TCPServer implements CommandLineRunner {
private Integer port;
@Override
public void run(String... args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
(bossGroup, workerGroup)
.channel()
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = ();
(new StringEncoder());
(new StringDecoder());
(new TCPServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = (port).sync();
("TCP server started and listening on port " + port);
().closeFuture().sync();
} finally {
();
();
}
}
}
配置文件
tcp:
server:
port: 8888 #服务器端口
配置TCPServerHandler
@Slf4j
@Component
public class TCPServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
("收到客户端消息:/n"+ msg);
Object parse = (msg);
("parse = " + parse);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
("TCPServer出现异常", cause);
();
}
}
TCPClient
客户端的配置大同小异
Netty依赖
<dependency>
<groupId></groupId>
<artifactId>netty-all</artifactId>
<version>4.1.</version>
</dependency>
配置TCPClient
@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "")
public class TCPClient implements CommandLineRunner {
private String host ;
private Integer port;
@Override
public void run(String... args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel()
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ();
(new StringEncoder());
(new StringDecoder());
(new TCPClientHandler());
}
});
ChannelFuture future = (host, port).sync();
("TCPClient Start , Connect host:"+host+":"+port);
().closeFuture().sync();
} catch (Exception e) {
("TCPClient Error", e);
} finally {
();
}
}
}
配置文件
tcp:
client:
port: 8080 #连接的服务器端口
host: 127.0.0.1 #连接的服务器域名
配置TCPServerHandler
@Slf4j
@Component
public class TCPClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
("Receive TCPServer Message:\n"+ msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
("TCPClient Error", cause);
();
}
}
这样就完成了整个搭建过程,重要的就是服务端的端口和客户端连接服务端的URL和接受消息的处理方式,其他的细节可以自己慢慢探索.