SpringBoot快速搭建TCP服務端和客戶端全過程
由于工作需要,研究了SpringBoot搭建TCP通信的過程,對于工程需要的小伙伴,只是想快速搭建一個可用的服務。
其他的教程看了許多,感覺講得太復雜,很容易弄亂,這里我只講效率,展示快速搭建過程。
TCPServer
由于TCP協(xié)議是Netty實現(xiàn)的,所以引入Netty的依賴
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency>
配置TCPServer
@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "tcp.server")
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();
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
pipeline.addLast(new TCPServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = bootstrap.bind(port).sync();
log.info("TCP server started and listening on port " + port);
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}application.yml配置文件
tcp: server: port: 8888 #服務器端口
配置TCPServerHandler
@Slf4j
@Component
public class TCPServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
log.info("收到客戶端消息:/n"+ msg);
Object parse = JSONUtils.parse(msg);
System.out.println("parse = " + parse);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.error("TCPServer出現(xiàn)異常", cause);
ctx.close();
}
}TCPClient
客戶端的配置大同小異
Netty依賴
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency>
配置TCPClient
@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "tcp.client")
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(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringEncoder());
pipeline.addLast(new StringDecoder());
pipeline.addLast(new TCPClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
log.info("TCPClient Start , Connect host:"+host+":"+port);
future.channel().closeFuture().sync();
} catch (Exception e) {
log.error("TCPClient Error", e);
} finally {
group.shutdownGracefully();
}
}
}application.yml配置文件
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) {
log.info("Receive TCPServer Message:\n"+ msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.error("TCPClient Error", cause);
ctx.close();
}
}這樣就完成了整個搭建過程,重要的就是服務端的端口和客戶端連接服務端的URL和接受消息的處理方式,其他的細節(jié)可以自己慢慢探索。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
mybatis取別名typeAliases標簽的位置放錯導致報錯的解決
這篇文章主要介紹了mybatis取別名typeAliases標簽的位置放錯導致報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
java 使用memcached以及spring 配置memcached完整實例代碼
本篇文章主要介紹了java 使用memcached以及spring 配置memcached完整實例代碼,具有一定的參考價值,有興趣的可以了解一下2017-07-07
解決spring懶加載以及@PostConstruct結合的坑
這篇文章主要介紹了解決spring懶加載以及@PostConstruct結合的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12

