Springboot2整合netty4.0

Springboot2整合netty4.0

在這裏插入圖片描述

前端:

window.CHAT = {
				socket: null,
				init: function() {
					if (window.WebSocket) {
						CHAT.socket = new WebSocket("ws://192.168.1.10:8088/ws");
						CHAT.socket.onopen = function() {
							console.log("連接建立成功...");
						},
						CHAT.socket.onclose = function() {
							console.log("連接關閉...");
						},
						CHAT.socket.onerror = function() {
							console.log("發生錯誤...");
						},
						CHAT.socket.onmessage = function(e) {
							console.log("接受到消息:" + e.data);
							var receiveMsg = document.getElementById("receiveMsg");
							var html = receiveMsg.innerHTML;
							receiveMsg.innerHTML = html + "<br/>" + e.data;
						}
					} else {
						alert("瀏覽器不支持websocket協議...");
					}
				},
				chat: function() {
					var msg = document.getElementById("msgContent");
					CHAT.socket.send(msg.value);
				}
			};
			
			CHAT.init();

後端:整合netty server
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();

	// websocket 基於http協議,所以要有http編解碼器
	pipeline.addLast(new HttpServerCodec());
	// 對寫大數據流的支持 
	pipeline.addLast(new ChunkedWriteHandler());
	// 對httpMessage進行聚合,聚合成FullHttpRequest或FullHttpResponse
	// 幾乎在netty中的編程,都會使用到此hanler
	pipeline.addLast(new HttpObjectAggregator(1024*64));
	
	// ====================== 以上是用於支持http協議    ======================
	
	
	
	// ====================== 增加心跳支持 start    ======================
	// 針對客戶端,如果在1分鐘時沒有向服務端發送讀寫心跳(ALL),則主動斷開
	// 如果是讀空閒或者寫空閒,不處理
	pipeline.addLast(new IdleStateHandler(8, 10, 12));
	// 自定義的空閒狀態檢測
	pipeline.addLast(new HeartBeatHandler());
	// ====================== 增加心跳支持 end    ======================
	
	
	
	
	// ====================== 以下是支持httpWebsocket ======================
	
	/**
	 * websocket 服務器處理的協議,用於指定給客戶端連接訪問的路由 : /ws
	 * 本handler會幫你處理一些繁重的複雜的事
	 * 會幫你處理握手動作: handshaking(close, ping, pong) ping + pong = 心跳
	 * 對於websocket來講,都是以frames進行傳輸的,不同的數據類型對應的frames也不同
	 */
	pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
	
	// 自定義的handler
	pipeline.addLast(new ChatHandler());
}

源碼下載:http://47.98.237.162/detail/1/181

下載源碼後,記住分享喲!

第一步:微信關注公衆號豔學網!

第二步:關注後打開菜單“豔輝福利”——“java福利”,轉發文章至朋友圈。

長按自動識別二維碼,即可關注微信公衆號“豔學網”
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章