SpringBoot整合Netty實(shí)現(xiàn)WebSocket的示例代碼
一、pom.xml依賴配置
<!-- netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.50.Final</version>
</dependency>二、代碼
2.1、NettyServer 類
package com.wangjing.socket.server;
import com.wangjing.socket.handler.CoordinationSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
public class CoordinationNettyServer {
private final int port;
public CoordinationNettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap sb = new ServerBootstrap();
sb.option(ChannelOption.SO_BACKLOG, 1024);
sb.group(group, bossGroup) // 綁定線程池
.channel(NioServerSocketChannel.class) // 指定使用的channel
.localAddress(this.port)// 綁定監(jiān)聽端口
.childHandler(new ChannelInitializer<SocketChannel>() { // 綁定客戶端連接時(shí)候觸發(fā)操作
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//websocket協(xié)議本身是基于http協(xié)議的,所以這邊也要使用http解編碼器
ch.pipeline().addLast(new HttpServerCodec());
//以塊的方式來寫的處理器
ch.pipeline().addLast(new ChunkedWriteHandler());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));
ch.pipeline().addLast(new CoordinationSocketHandler());//自定義消息處理類
}
});
ChannelFuture cf = sb.bind().sync(); // 服務(wù)器異步創(chuàng)建綁定
System.out.println(CoordinationNettyServer.class + "已啟動(dòng),正在監(jiān)聽: " + cf.channel().localAddress());
cf.channel().closeFuture().sync(); // 關(guān)閉服務(wù)器通道
} finally {
group.shutdownGracefully().sync(); // 釋放線程池資源
bossGroup.shutdownGracefully().sync();
}
}
}
2.2、SocketHandler 類
package com.wangjing.socket.handler;
import com.wangjing.socket.pool.CoordinationChannelHandlerPool;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
public class CoordinationSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("與客戶端建立連接,通道開啟!");
//添加到channelGroup通道組
CoordinationChannelHandlerPool.channelGroup.add(ctx.channel());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("與客戶端斷開連接,通道關(guān)閉!");
//從channelGroup通道組刪除
CoordinationChannelHandlerPool.channelGroup.remove(ctx.channel());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
//接收的消息
System.out.println(String.format("收到客戶端%s的數(shù)據(jù):%s", ctx.channel().id(), msg.text()));
// 單獨(dú)發(fā)消息
// sendMessage(ctx);
// 群發(fā)消息
sendAllMessage();
}
private void sendMessage(ChannelHandlerContext ctx) throws InterruptedException {
String message = "我是服務(wù)器,你好呀";
ctx.writeAndFlush(new TextWebSocketFrame("hello"));
}
private void sendAllMessage() {
String message = "我是服務(wù)器,這是群發(fā)消息";
CoordinationChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(message));
}
}2.3、ChannelHandlerPool 類
package com.wangjing.socket.pool;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
public class CoordinationChannelHandlerPool {
public CoordinationChannelHandlerPool() {
}
//可以存儲(chǔ)userId與ChannelId的映射表
// public static ConcurrentHashMap<String, ChannelId> channelIdMap = new ConcurrentHashMap<>();
//channelGroup通道組
public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}2.4、Application啟動(dòng)類
package com.wangjing.socket;
import com.wangjing.socket.server.CoordinationNettyServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.wangjing")
public class SocketApplication {
public static void main(String[] args) {
SpringApplication.run(SocketApplication.class, args);
try {
new CoordinationNettyServer(8804).start();
} catch (Exception e) {
System.out.println("NettyServerError:" + e.getMessage());
}
}
}三、測(cè)試
websocket 在線測(cè)試推薦:在線websocket測(cè)試-online tool-postjson

到此這篇關(guān)于SpringBoot整合Netty實(shí)現(xiàn)WebSocket的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot整合Netty實(shí)現(xiàn)WebSocket內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot3集成WebSocket的全過程
- SpringBoot整合Netty+Websocket實(shí)現(xiàn)消息推送的示例代碼
- springboot整合websocket后啟動(dòng)報(bào)錯(cuò)(javax.websocket.server.ServerContainer not available)
- SpringBoot 整合WebSocket 前端 uniapp 訪問的詳細(xì)方法
- Springboot整合WebSocket實(shí)戰(zhàn)教程
- SpringBoot整合WebSocket的客戶端和服務(wù)端的實(shí)現(xiàn)代碼
- springboot整合websocket最基礎(chǔ)入門使用教程詳解
- 通過實(shí)例講解springboot整合WebSocket
- SpringBoot3整合WebSocket詳細(xì)指南
相關(guān)文章
springboot中Getmapping獲取參數(shù)的實(shí)現(xiàn)方式
這篇文章主要介紹了springboot中Getmapping獲取參數(shù)的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
SpringBoot項(xiàng)目中的多數(shù)據(jù)源支持的方法
本篇文章主要介紹了SpringBoot項(xiàng)目中的多數(shù)據(jù)源支持的方法,主要介紹在SpringBoot項(xiàng)目中利用SpringDataJpa技術(shù)如何支持多個(gè)數(shù)據(jù)庫的數(shù)據(jù)源,有興趣的可以了解一下2017-10-10
在Java項(xiàng)目中實(shí)現(xiàn)日志輸出的技巧分享
日志是開發(fā)過程中不可或缺的一部分,它可以幫助我們追蹤代碼的執(zhí)行過程、排查問題以及監(jiān)控系統(tǒng)運(yùn)行狀況,然而,大多數(shù)開發(fā)人員在編寫日志時(shí)往往只關(guān)注于輸出必要的信息,而忽略了日志的可讀性和美觀性,本文將介紹如何在Java項(xiàng)目中實(shí)現(xiàn)漂亮的日志輸出2023-10-10
淺談SpringBoot2.4 配置文件加載機(jī)制大變化
這篇文章主要介紹了淺談SpringBoot2.4 配置文件加載機(jī)制大變化,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
SpringBoot+WebSocket實(shí)現(xiàn)消息推送功能
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議。本文將通過SpringBoot集成WebSocket實(shí)現(xiàn)消息推送功能,感興趣的可以了解一下2022-08-08
IDEA 當(dāng)前在線人數(shù)和歷史訪問量的示例代碼
這篇文章主要介紹了IDEA 當(dāng)前在線人數(shù)和歷史訪問量的實(shí)例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08

