Netty進階篇之websocket發送消息(8)

序言:Netty進階篇之簡單版websocket發消息(7) 大概和下面的代碼就成類似,只不過上一篇博客更加簡單一些。javascript

一、pom文件

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.25.Final</version>
</dependency>

二、index.html

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8" />
      <title></title>
   </head>
   <body>
      <div>發送消息:</div>
      <input type="text" id="msgContent"/>
      <input type="button" value="點我發送" onclick="CHAT.chat()"/>
      
      <div>接受消息:</div>
      <div id="receiveMsg" style="background-color: gainsboro;"></div>
      
      <script type="application/javascript">
         
         window.CHAT = {
            socket: null,
            init: function() {
               if (window.WebSocket) {
                  CHAT.socket = new WebSocket("ws://192.168.31.160: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();
      </script>
   </body>
</html>

三、main函數

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class WSServer {

   public static void main(String[] args) throws Exception {
      
      //定義一對線程組 
      // 主線程組, 用於接受客戶端的鏈接,可是不作任何處理,跟老闆同樣,不作事      
      EventLoopGroup mainGroup = new NioEventLoopGroup();
      // 從線程組, 老闆線程組會把任務丟給他,讓手下線程組去作任務
      EventLoopGroup subGroup = new NioEventLoopGroup();
      
      try {
         // netty服務器的建立, ServerBootstrap 是一個啓動類
         ServerBootstrap server = new ServerBootstrap();
         server.group(mainGroup, subGroup)    // 設置主從線程組
            .channel(NioServerSocketChannel.class)    // 設置nio的雙向通道
            .childHandler(new WSServerInitialzer());  //// 子處理器,用於處理workerGroup
         
         // 啓動server,而且設置8088爲啓動的端口號,同時啓動方式爲同步
         ChannelFuture future = server.bind(8088).sync();
         
         future.channel().closeFuture().sync();
      } finally {
         // 監聽關閉的channel,設置位同步方式
         mainGroup.shutdownGracefully();
         subGroup.shutdownGracefully();
      }
   }
}

四、初始化類

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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 WSServerInitialzer extends ChannelInitializer<SocketChannel> {

   @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協議    ======================
      
      // ====================== 如下是支持httpWebsocket ======================
      
      /**
       * websocket 服務器處理的協議,用於指定給客戶端鏈接訪問的路由 : /ws
       * 本handler會幫你處理一些繁重的複雜的事
       * 會幫你處理握手動做: handshaking(close, ping, pong) ping + pong = 心跳
       * 對於websocket來說,都是以frames進行傳輸的,不一樣的數據類型對應的frames也不一樣
       */
      pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
      
      // 自定義的handler
      pipeline.addLast(new ChatHandler());
   }
}

五、助手類

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 
 * @Description: 處理消息的handler
 * TextWebSocketFrame: 在netty中,是用於爲websocket專門處理文本的對象,frame是消息的載體
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

   // 用於記錄和管理全部客戶端的channle
   private static ChannelGroup clients = 
         new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
   
   @Override
   protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) 
         throws Exception {
      // 獲取客戶端傳輸過來的消息
      String content = msg.text();
      System.out.println("接受到的數據:" + content);

      //相似於for循環
      clients.writeAndFlush(
            new TextWebSocketFrame(
                  "[服務器在]" + LocalDateTime.now() 
                  + "接受到消息, 消息爲:" + content));
   }

   /**
    * 當客戶端鏈接服務端以後(打開鏈接)
    * 獲取客戶端的channle,而且放到ChannelGroup中去進行管理
    */
   @Override
   public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
      clients.add(ctx.channel());
   }

   @Override
   public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
      // 當觸發handlerRemoved,ChannelGroup會自動移除對應客戶端的channel
//    clients.remove(ctx.channel());
      System.out.println("客戶端斷開,channle對應的長id爲:" 
                     + ctx.channel().id().asLongText());
      System.out.println("客戶端斷開,channle對應的短id爲:" 
                     + ctx.channel().id().asShortText());
   }
}

六、測試

運行index.htmlhtml

發送消息,以下server端返回消息java

相關文章
相關標籤/搜索