SpringBoot快速搭建TCP服務(wù)端和客戶端全過(guò)程
由于工作需要,研究了SpringBoot搭建TCP通信的過(guò)程,對(duì)于工程需要的小伙伴,只是想快速搭建一個(gè)可用的服務(wù)。
其他的教程看了許多,感覺(jué)講得太復(fù)雜,很容易弄亂,這里我只講效率,展示快速搭建過(guò)程。
TCPServer
由于TCP協(xié)議是Netty實(shí)現(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 #服務(wù)器端口
配置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 #連接的服務(wù)器端口 host: 127.0.0.1 #連接的服務(wù)器域名
配置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();
}
}這樣就完成了整個(gè)搭建過(guò)程,重要的就是服務(wù)端的端口和客戶端連接服務(wù)端的URL和接受消息的處理方式,其他的細(xì)節(jié)可以自己慢慢探索。
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis取別名typeAliases標(biāo)簽的位置放錯(cuò)導(dǎo)致報(bào)錯(cuò)的解決
這篇文章主要介紹了mybatis取別名typeAliases標(biāo)簽的位置放錯(cuò)導(dǎo)致報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
java 使用memcached以及spring 配置memcached完整實(shí)例代碼
本篇文章主要介紹了java 使用memcached以及spring 配置memcached完整實(shí)例代碼,具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07
解決spring懶加載以及@PostConstruct結(jié)合的坑
這篇文章主要介紹了解決spring懶加載以及@PostConstruct結(jié)合的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
Java實(shí)現(xiàn)求數(shù)組最長(zhǎng)子序列算法示例
這篇文章主要介紹了Java實(shí)現(xiàn)求數(shù)組最長(zhǎng)子序列算法,涉及java針對(duì)數(shù)組的遞歸遍歷、判斷相關(guān)操作技巧,需要的朋友可以參考下2018-07-07
Java實(shí)現(xiàn)提取QSV文件視頻內(nèi)容
QSV是一種加密的視頻文件格式。是愛(ài)奇藝公司研發(fā)的一種視頻文件格式,這篇文章主要為大家介紹了如何利用Java實(shí)現(xiàn)提取QSV文件視頻內(nèi)容,感興趣的可以了解一下2023-03-03
jdbc連接數(shù)據(jù)庫(kù)實(shí)例詳解
在本篇內(nèi)容里小編給大家分享了關(guān)于jdbc如何連接數(shù)據(jù)庫(kù)的相關(guān)知識(shí)點(diǎn)內(nèi)容,需要的朋友們學(xué)習(xí)下。2019-02-02

