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

SpringBoot2+Netty+WebSocket(netty實(shí)現(xiàn)websocket支持URL參數(shù))問題記錄

 更新時(shí)間:2023年12月20日 14:45:09   作者:Moshow鄭鍇  
Netty?是一個(gè)利用?Java?的高級(jí)網(wǎng)絡(luò)的能力,隱藏其背后的復(fù)雜性而提供一個(gè)易于使用的?API?的客戶端/服務(wù)器框架,這篇文章主要介紹了SpringBoot2+Netty+WebSocket(netty實(shí)現(xiàn)websocket,支持URL參數(shù)),需要的朋友可以參考下

關(guān)于Netty

Netty 是一個(gè)利用 Java 的高級(jí)網(wǎng)絡(luò)的能力,隱藏其背后的復(fù)雜性而提供一個(gè)易于使用的 API 的客戶端/服務(wù)器框架。

更新

2019-7-11 新增URL參數(shù)支持,并解決了帶參URL導(dǎo)致的連接自動(dòng)斷開問題,感謝大家的支持。

MAVEN依賴

<dependencies>
		<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-all</artifactId>
			<version>4.1.36.Final</version>
		</dependency>
	</dependencies>

SpringBootApplication

啟動(dòng)器中需要new一個(gè)NettyServer,并顯式調(diào)用啟動(dòng)netty。

@SpringBootApplication
public class SpringCloudStudyDemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringCloudStudyDemoApplication.class,args);
		try {
			new NettyServer(12345).start();
			System.out.println("https://blog.csdn.net/moshowgame");
			System.out.println("http://127.0.0.1:6688/netty-websocket/index");
		}catch(Exception e) {
			System.out.println("NettyServerError:"+e.getMessage());
		}
	}
}

NettyServer

啟動(dòng)的NettyServer,這里進(jìn)行配置

/**
 * NettyServer Netty服務(wù)器配置
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
public class NettyServer {
    private final int port;
    public NettyServer(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 {
                            System.out.println("收到新連接");
                            //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", null, true, 65536 * 10));
                            ch.pipeline().addLast(new MyWebSocketHandler());
                        }
                    });
            ChannelFuture cf = sb.bind().sync(); // 服務(wù)器異步創(chuàng)建綁定
            System.out.println(NettyServer.class + " 啟動(dòng)正在監(jiān)聽: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 關(guān)閉服務(wù)器通道
        } finally {
            group.shutdownGracefully().sync(); // 釋放線程池資源
            bossGroup.shutdownGracefully().sync();
        }
    }
}

MyChannelHandlerPool

通道組池,管理所有websocket連接

/**
 * MyChannelHandlerPool
 * 通道組池,管理所有websocket連接
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
public class MyChannelHandlerPool {
    public MyChannelHandlerPool(){}
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}

MyWebSocketHandler

處理ws一下幾種情況:

  • channelActive與客戶端建立連接
  • channelInactive與客戶端斷開連接
  • channelRead0客戶端發(fā)送消息處理
/**
 * NettyServer Netty服務(wù)器配置
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
public class NettyServer {
    private final int port;
    public NettyServer(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 {
                            System.out.println("收到新連接");
                            //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 MyWebSocketHandler());
                        }
                    });
            ChannelFuture cf = sb.bind().sync(); // 服務(wù)器異步創(chuàng)建綁定
            System.out.println(NettyServer.class + " 啟動(dòng)正在監(jiān)聽: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 關(guān)閉服務(wù)器通道
        } finally {
            group.shutdownGracefully().sync(); // 釋放線程池資源
            bossGroup.shutdownGracefully().sync();
        }
    }
}

socket.html

主要是連接ws,發(fā)送消息,以及消息反饋

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Netty-Websocket</title>
    <script type="text/javascript">
        // by zhengkai.blog.csdn.net
        var socket;
        if(!window.WebSocket){
            window.WebSocket = window.MozWebSocket;
        }
        if(window.WebSocket){
            socket = new WebSocket("ws://127.0.0.1:12345/ws");
            socket.onmessage = function(event){
                var ta = document.getElementById('responseText');
                ta.value += event.data+"\r\n";
            };
            socket.onopen = function(event){
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服務(wù)器。。。。。。連接  \r\n";
            };
            socket.onclose = function(event){
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服務(wù)器。。。。。。關(guān)閉 \r\n";
            };
        }else{
            alert("您的瀏覽器不支持WebSocket協(xié)議!");
        }
        function send(message){
            if(!window.WebSocket){return;}
            if(socket.readyState == WebSocket.OPEN){
                socket.send(message);
            }else{
                alert("WebSocket 連接沒有建立成功!");
            }
        }
    </script>
</head>
<body>
<form onSubmit="return false;">
    <label>ID</label><input type="text" name="uid" value="${uid!!}" /> <br />
    <label>TEXT</label><input type="text" name="message" value="這里輸入消息" /> <br />
    <br /> <input type="button" value="發(fā)送ws消息"
                  onClick="send(this.form.uid.value+':'+this.form.message.value)" />
    <hr color="black" />
    <h3>服務(wù)端返回的應(yīng)答消息</h3>
    <textarea id="responseText" style="width: 1024px;height: 300px;"></textarea>
</form>
</body>
</html>

Controller

寫好了html當(dāng)然還需要一個(gè)controller來引導(dǎo)頁面。

@RestController
public class IndexController {
	@GetMapping("/index")
	public ModelAndView  index(){
		ModelAndView mav=new ModelAndView("socket");
		mav.addObject("uid", RandomUtil.randomNumbers(6));
		return mav;
	}
}

效果演示

思路優(yōu)化

由于netty不能像默認(rèn)的websocket一樣設(shè)置一些PathVariable例如{uid}等參數(shù)(暫未發(fā)現(xiàn)可以,如果有發(fā)現(xiàn)歡迎補(bǔ)充),所以很多時(shí)候發(fā)送到后臺(tái)的報(bào)文可以設(shè)置一些特殊的格式,例如上文的004401:大家好,可以分解為userid:text,當(dāng)然userid也可以是加密的一些報(bào)文,甚至可以學(xué)習(xí)其他報(bào)文一樣設(shè)置加密區(qū),這取決于大家的業(yè)務(wù)需要. (已更新解決方案)

后言

項(xiàng)目已經(jīng)整合進(jìn)開源項(xiàng)目spring-cloud-study的子模塊spring-cloud-study-netty-websocket,作為對(duì)websocket體系的補(bǔ)充,對(duì)SpringBoot2.0集成WebSocket,實(shí)現(xiàn)后臺(tái)向前端推送信息 的完善。

改造netty支持url參數(shù)

最新改造的項(xiàng)目代碼已經(jīng)上傳,克服了使用url會(huì)導(dǎo)致連接斷開的問題,詳情請(qǐng)看spring-cloud-study

首先,調(diào)整一下加載handler的順序,優(yōu)先MyWebSocketHandler在WebSocketServerProtocolHandler之上。

ch.pipeline().addLast(new MyWebSocketHandler());
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));

其次,改造MyWebSocketHandlerchannelRead方法,首次連接會(huì)是一個(gè)FullHttpRequest類型,可以通過FullHttpRequest.uri()獲取完整ws的URL地址,之后接受信息的話,會(huì)是一個(gè)TextWebSocketFrame類型。

public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("與客戶端建立連接,通道開啟!");
        //添加到channelGroup通道組
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("與客戶端斷開連接,通道關(guān)閉!");
        //添加到channelGroup 通道組
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次連接是FullHttpRequest,處理參數(shù) by zhengkai.blog.csdn.net
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            Map paramMap=getUrlParams(uri);
            System.out.println("接收到的參數(shù)是:"+JSON.toJSONString(paramMap));
            //如果url包含參數(shù),需要處理
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            }
        }else if(msg instanceof TextWebSocketFrame){
            //正常的TEXT消息類型
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;
            System.out.println("客戶端收到服務(wù)器數(shù)據(jù):" +frame.text());
            sendAllMessage(frame.text());
        }
        super.channelRead(ctx, msg);
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
    }
    private void sendAllMessage(String message){
        //收到信息后,群發(fā)給所有channel
        MyChannelHandlerPool.channelGroup.writeAndFlush( new TextWebSocketFrame(message));
    }
    private static Map getUrlParams(String url){
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;
        }else{
            return map;
        }
    }
}

html中的ws地址也進(jìn)行改造

socket = new WebSocket("ws://127.0.0.1:12345/ws?uid=666&gid=777");

改造后控制臺(tái)輸出情況

收到新連接
與客戶端建立連接,通道開啟!
接收到的參數(shù)是:{"uid":"666","gid":"777"}
/ws
客戶端收到服務(wù)器數(shù)據(jù):142531:這里輸入消息
客戶端收到服務(wù)器數(shù)據(jù):142531:這里輸入消息
客戶端收到服務(wù)器數(shù)據(jù):142531:這里輸入消息

failed: WebSocket opening handshake timed out

聽說是ssl wss的情況下才會(huì)出現(xiàn),來自 @around-gao 的解決方法:

把MyWebSocketHandler和WebSocketServerProtocolHandler調(diào)下順序就好了。

到此這篇關(guān)于SpringBoot2+Netty+WebSocket(netty實(shí)現(xiàn)websocket,支持URL參數(shù))的文章就介紹到這了,更多相關(guān)SpringBoot2 Netty WebSocket內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring通過<import>標(biāo)簽導(dǎo)入外部配置文件

    Spring通過<import>標(biāo)簽導(dǎo)入外部配置文件

    之前文章里我們講到Spring加載Xml配置文件的細(xì)節(jié),那么加載完了我們肯定要解析這個(gè)配置文件中定義的元素。這篇我們首先來分析下Spring是如何通過標(biāo)簽導(dǎo)入外部配置文件的。
    2021-06-06
  • SpringBoot org.springframework.beans.factory.UnsatisfiedDependencyException依賴注入異常

    SpringBoot org.springframework.beans.factory.Unsatisfie

    本文主要介紹了SpringBoot org.springframework.beans.factory.UnsatisfiedDependencyException依賴注入異常,文中通過示例代碼介紹的很詳細(xì),具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • Java中的Pair詳細(xì)

    Java中的Pair詳細(xì)

    這篇文章主要介紹Java中的很有意思的Pair,下面文章會(huì)以Pair用法展開,感興趣的小伙伴可以參考下面文章的具體內(nèi)容
    2021-10-10
  • SpringBoot@Aspect 打印訪問請(qǐng)求和返回?cái)?shù)據(jù)方式

    SpringBoot@Aspect 打印訪問請(qǐng)求和返回?cái)?shù)據(jù)方式

    這篇文章主要介紹了SpringBoot@Aspect 打印訪問請(qǐng)求和返回?cái)?shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • SpringMVC配置攔截器實(shí)現(xiàn)登錄控制的方法

    SpringMVC配置攔截器實(shí)現(xiàn)登錄控制的方法

    這篇文章主要介紹了SpringMVC配置攔截器實(shí)現(xiàn)登錄控制的方法,SpringMVC讀取Cookie判斷用戶是否登錄,對(duì)每一個(gè)action都要進(jìn)行判斷,有興趣的可以了解一下。
    2017-03-03
  • Android Studio中ButterKnife插件的安裝與使用詳解

    Android Studio中ButterKnife插件的安裝與使用詳解

    本篇文章主要介紹了Android Studio中ButterKnife插件的安裝與使用詳解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • 關(guān)于MyBatis中SqlSessionFactory和SqlSession簡解

    關(guān)于MyBatis中SqlSessionFactory和SqlSession簡解

    這篇文章主要介紹了MyBatis中SqlSessionFactory和SqlSession簡解,具有很好的參考價(jià)值,希望大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • 解決spring?security?loginProcessingUrl無效問題

    解決spring?security?loginProcessingUrl無效問題

    這篇文章主要介紹了解決spring?security?loginProcessingUrl無效問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Java實(shí)現(xiàn)Word文檔變量的添加與修改操作詳解

    Java實(shí)現(xiàn)Word文檔變量的添加與修改操作詳解

    文檔變量以鍵值對(duì)的形式存儲(chǔ)在文檔的元數(shù)據(jù)中,通過在正文中插入域(Field)來引用這些變量,可以實(shí)現(xiàn)一處修改全局同步的效果,本文將介紹如何利用 Java 代碼,通過一個(gè)第三方的 Word 文檔處理庫,實(shí)現(xiàn)文檔變量的添加與修改操作,有需要的小伙伴可以了解下
    2026-05-05
  • idea導(dǎo)入jar包的詳細(xì)圖文教程

    idea導(dǎo)入jar包的詳細(xì)圖文教程

    這篇文章主要給大家介紹了關(guān)于idea導(dǎo)入jar包的詳細(xì)圖文教程,文中通過圖文將導(dǎo)入的步驟介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2023-03-03

最新評(píng)論

新干县| 岚皋县| 九江县| 孝昌县| 盖州市| 伊金霍洛旗| 莱西市| 汤阴县| 平潭县| 全南县| 英吉沙县| 安徽省| 临泉县| 行唐县| 昂仁县| 华坪县| 十堰市| 临邑县| 临潭县| 涡阳县| 黄石市| 瑞丽市| 商河县| 鄄城县| 五河县| 繁峙县| 锡林浩特市| 江陵县| 鄂托克旗| 盖州市| 嵩明县| 萨迦县| 翁牛特旗| 义马市| 台前县| 大厂| 浑源县| 于都县| 芜湖市| 银川市| 德清县|