1. 程式人生 > >Netty實現WebSocket通訊案例

Netty實現WebSocket通訊案例

Netty開發服務端,HTML實現客戶端,實現服務端與客戶端的實時互動。

1.儲存整個工程的全域性配置:

package com.research.netty.WebSocket;

import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/***
 * 儲存整個工程的全域性配置
 */
public class NettyConfig {
    /***
     * 儲存每一個客戶端接入進來時的Channel物件
     */
    public  static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}

2.接收/處理/響應客戶端websocket請求的核心業務處理類

package com.research.netty.WebSocket;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.CharsetUtil;

/**
 * 接收/處理/響應客戶端websocket請求的核心業務處理類
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler<Object> {

    //握手
    private WebSocketServerHandshaker handshaker;
    private static final String WEB_SOCKET_URL = "ws://localhost:8888/websocket";

    //客戶端與服務端建立連線的時候呼叫
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        NettyConfig.group.add(ctx.channel());
        System.out.println("客戶端與服務端連線開啟...");
    }

    //客戶端與服務端斷開連線的時候呼叫
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        NettyConfig.group.remove(ctx.channel());
        System.out.println("客戶端與服務端連線關閉...");
    }

    //服務端接收客戶端傳送過來的資料結束之後呼叫
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    //工程出現異常的時候呼叫
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    //服務端處理客戶端websocket請求的核心方法
    @Override
    protected void messageReceived(ChannelHandlerContext context, Object msg) throws Exception {
        //處理客戶端向服務端發起http握手請求的業務
        if (msg instanceof FullHttpRequest) {
            handHttpRequest(context, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) { //處理websocket連線業務
            handWebsocketFrame(context, (WebSocketFrame) msg);
        }
    }

    /**
     * 處理客戶端與服務端之前的websocket業務
     *
     * @param ctx
     * @param frame
     */
    private void handWebsocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        //判斷是否是關閉websocket的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        }
        //判斷是否是ping訊息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        //判斷是否是二進位制訊息,如果是二進位制訊息,丟擲異常(我們這個例子不支援二進位制訊息)
        if (!(frame instanceof TextWebSocketFrame)) {
            System.out.println("目前我們不支援二進位制訊息");
            throw new RuntimeException("【" + this.getClass().getName() + "】不支援訊息");
        }
        //返回應答訊息
        //獲取客戶端向服務端傳送的訊息
        String request = ((TextWebSocketFrame) frame).text();
        System.out.println("服務端收到客戶端的訊息====>>>" + request);
        TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString()
                + ctx.channel().id()
                + " ===>>> "
                + request);
        //群發,服務端向每個連線上來的客戶端群發訊息
        NettyConfig.group.writeAndFlush(tws);

    }

    /**
     * 處理客戶端向服務端發起http握手請求的業務
     *
     * @param ctx
     * @param req
     */
    private void handHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        if (!req.getDecoderResult().isSuccess()
                || !("websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req,
                    new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                WEB_SOCKET_URL, null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    /**
     * 服務端向客戶端響應訊息
     *
     * @param ctx
     * @param req
     * @param res
     */
    private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req,
                                  DefaultFullHttpResponse res) {
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        //服務端向客戶端傳送資料
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

3.初始化連線時候的各個元件

package com.research.netty.WebSocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 初始化連線時候的各個元件
 */
public class MyWebSocketChannelHandler extends ChannelInitializer<SocketChannel> {

   @Override
   protected void initChannel(SocketChannel e) throws Exception {
      e.pipeline().addLast("http-codec", new HttpServerCodec());
      e.pipeline().addLast("aggregator", new HttpObjectAggregator(65536));
      e.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
      e.pipeline().addLast("handler", new MyWebSocketHandler());
   }

}

4.程式的入口,負責啟動應用

package com.research.netty.WebSocket;

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

/**
 * 程式的入口,負責啟動應用
 */
public class Main {
   public static void main(String[] args) {
      //配置服務端NIO執行緒組
      EventLoopGroup bossGroup = new NioEventLoopGroup();
      EventLoopGroup workGroup = new NioEventLoopGroup();
      try {
         ServerBootstrap b = new ServerBootstrap();
         b.group(bossGroup, workGroup);
         b.channel(NioServerSocketChannel.class);
         b.childHandler(new MyWebSocketChannelHandler());
         System.out.println("服務端開啟等待客戶端連線....");
         Channel ch = b.bind(8888).sync().channel();
         ch.closeFuture().sync();
         
      } catch (Exception e) {
         e.printStackTrace();
      }finally{
         //優雅的退出程式
         bossGroup.shutdownGracefully();
         workGroup.shutdownGracefully();
      }
   }
}

5.html

<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset = utf-8"/>
      <title>WebSocket客戶端</title>
   <script type="text/javascript">
      var socket;
      if(!window.WebSocket){
         window.WebSocket = window.MozWebSocket;
      }

      if(window.WebSocket){
         socket = new WebSocket("ws://localhost:8888/websocket");
         socket.onmessage = function(event){
            var ta = document.getElementById('responseContent');
            ta.value += event.data + "\r\n";
         };

         socket.onopen = function(event){
            var ta = document.getElementById('responseContent');
            ta.value = "你當前的瀏覽器支援WebSocket,請進行後續操作\r\n";
         };

         socket.onclose = function(event){
            var ta = document.getElementById('responseContent');
            ta.value = "";
            ta.value = "WebSocket連線已經關閉\r\n";
         };
      }else{
         alert("您的瀏覽器不支援WebSocket");
      }

        window.onbeforeunload = function(){
            ws.close();
        }

      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;">
         <input type = "text" name = "message" value = ""/>
         <br/><br/>
         <input type = "button" value = "傳送WebSocket請求訊息" onClick = "send(this.form.message.value)"/>
         <hr color="red"/>
         <h2>客戶端接收到服務端返回的應答訊息</h2>
         <textarea id = "responseContent" style = "width:1024px; height:300px"></textarea>
      </form>
   </body>
</html>

 

---摘自慕課網netty課程