最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Netty實(shí)現(xiàn)WebSocket的示例代碼

 更新時(shí)間:2022年05月12日 15:49:32   作者:JAVA·D·WangJing  
本文主要介紹了SpringBoot整合Netty實(shí)現(xiàn)WebSocket的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一、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)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Maven私服倉(cāng)庫(kù)Nexus配置小結(jié)

    Maven私服倉(cāng)庫(kù)Nexus配置小結(jié)

    Maven 私服是一種特殊的Maven遠(yuǎn)程倉(cāng)庫(kù),它是架設(shè)在局域網(wǎng)內(nèi)的倉(cāng)庫(kù)服務(wù),本文就來介紹一下Maven私服倉(cāng)庫(kù)Nexus配置小結(jié),具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-08-08
  • RestTemplate返回值中文亂碼問題

    RestTemplate返回值中文亂碼問題

    這篇文章主要介紹了RestTemplate返回值中文亂碼問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-04-04
  • springboot中Getmapping獲取參數(shù)的實(shí)現(xià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)目中的多數(shù)據(jù)源支持的方法,主要介紹在SpringBoot項(xiàng)目中利用SpringDataJpa技術(shù)如何支持多個(gè)數(shù)據(jù)庫(kù)的數(shù)據(jù)源,有興趣的可以了解一下
    2017-10-10
  • 在Java項(xiàng)目中實(shí)現(xiàn)日志輸出的技巧分享

    在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ī)制大變化

    這篇文章主要介紹了淺談SpringBoot2.4 配置文件加載機(jī)制大變化,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • SpringBoot+WebSocket實(shí)現(xiàn)消息推送功能

    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ù)和歷史訪問量的示例代碼

    這篇文章主要介紹了IDEA 當(dāng)前在線人數(shù)和歷史訪問量的實(shí)例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Mybatisplus主鍵生成策略算法解析

    Mybatisplus主鍵生成策略算法解析

    這篇文章主要介紹了Mybatisplus主鍵生成策略算法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • java日志打印的完全使用指南

    java日志打印的完全使用指南

    日志就是記錄程序的運(yùn)行軌跡,方便查找關(guān)鍵信息,也方便快速定位解決問題,下面這篇文章主要給大家介紹了關(guān)于java日志打印使用的相關(guān)資料,需要的朋友可以參考下
    2022-01-01

最新評(píng)論

山阴县| 盐亭县| 双江| 荥阳市| 大邑县| 炎陵县| 革吉县| 平顺县| 孟村| 镶黄旗| 手机| 延长县| 南郑县| 石泉县| 常宁市| 大安市| 黎平县| 芦山县| 鹰潭市| 杭锦后旗| 棋牌| 揭阳市| 文安县| 秭归县| 墨玉县| 新建县| 宣武区| 华阴市| 遵义县| 博客| 姚安县| 定陶县| 富蕴县| 临清市| 廊坊市| 罗源县| 青海省| 普定县| 抚宁县| 哈尔滨市| 临清市|