1. 程式人生 > >netty websocket

netty websocket

請求 obj ole ktr ets integer sockets nav 動態添加

WebSocketServer

package com.zhaowb.netty.ch11;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
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.stream.ChunkedWriteHandler; public class WebSocketServer { public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup();
try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline
= ch.pipeline(); pipeline.addLast("http-codec", new HttpServerCodec());// 添加 HttpServerCodec 將請求和應答消息編碼或解碼為HTTP 消息 pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); // 增加HttpObjectAggregator ,將HTTP 消息的多個部分組合成一條完整的HTTP消息 pipeline.addLast("http-chunked", new ChunkedWriteHandler());// 添加ChunkedWriteHandler,來向客戶端發送HTML5文件,主要用於支持瀏覽器和服務端進行WebSocket 通信。 pipeline.addLast("handle", new WebSocketServerHandler()); // 增加WebSocket 服務端的handler } }); Channel ch = b.bind(port).sync().channel(); System.out.println("Web socket server started at port : " + port + ‘.‘); System.out.println("Open your browser and navigate to http://localhost:" + port + ‘/‘); ch.closeFuture().sync(); } catch (Exception e) { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; if (args.length > 0) { try { port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { e.printStackTrace(); } } new WebSocketServer().run(port); } }

WebSocketServerHandler

package com.zhaowb.netty.ch11;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive;
import static io.netty.handler.codec.http.HttpHeaders.setContentLength;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;

public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final Logger logger = Logger.getLogger(WebSocketServerHandler.class.getName());

    private WebSocketServerHandshaker handshaker;

    /**
     * 第一次握手請求消息由HTTP協議承載,所有它是一個HTTP 消息,執行handleHttpRequest方法來處理WebSocket 握手請求。
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 傳統HTTP 接入
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {

        /**
         * 對握手請求消息進行判斷,如果消息頭中沒有包含Upgrade 字段或者它的值不是websocket。則返回HTTP 400響應
         */
        // 如果HTTP解碼失敗,返回HTTP異常
        if (!req.getDecoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, BAD_REQUEST));
            return;
        }

        // 構造握手響應返回,本機測試。
        /**
         * 握手請求簡單校驗通過之後,開始構造握手工廠,創建握手處理類 WebSocketServerHandshaker,通過它構造握手響應消息
         * 返回給客戶端,同時將WebSocket相關的編碼和解碼類動態添加到ChannelPipeline中,用於WebSocket消息的編解碼
         */
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws:localhost:8080/websocket", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    /**
     * 對WebSocket 請求消息進行處理,首先需要對控制幀進行判斷,如果是關閉鏈路的控制信息,就調用WebSocketServerHandshaker
     * 的close 方法關閉WebSocket連接,如果是維持鏈路的Ping消息,則構造Pong消息返回。
     * @param ctx
     * @param frame
     */
    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 判斷鏈路是否關閉
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 支持文本信息,不支持二進制
        if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }
        // 返回應答消息
        // 從TextWebSocketFrame中獲取請求消息字符串,對它處理通過後構造新的TextWebSocketFrame消息,返回給客戶端,
        // 由於握手應答時動態增加了TextWebSocketFrame的編碼類,所以直接發送TextWebSocketFrame對象。
        String request = ((TextWebSocketFrame) frame).text();
        if (logger.isLoggable(Level.FINE)) {
            logger.fine(String.format("%s received %s", ctx.channel()));
        }
        ctx.channel().write(new TextWebSocketFrame(request + " , 歡迎使用 Netty WebScoket服務,現在時刻:" + new Date().toString()));
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // 返回應答給客戶端
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            setContentLength(res, res.content().readableBytes());
        }
        // 如果是非 Keep-Alive ,關閉連接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

test.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    Netty WebSocket 時間服務器
</head>
<br>
<body>
<br>
<script type="text/javascript">
    var socket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8080/websocket");
        socket.onmessage = function (event) {
            var ta = document.getElementById(responseText);
            ta.value = "";
            ta.value = event.data
        };
        socket.onopen = function (event) {
            var ta = document.getElementById(responseText);
            ta.value = "打開WebSocket服務正常,瀏覽器支持WebSocket!";
        };
        socket.onclose = function (event) {
            var ta = document.getElementById(responseText);
            ta.value = "";
            ta.value = "WebSocket 關閉!";
        };
    }
    else {
        alert("抱歉,您的瀏覽器不支持WebSocket協議!");
    }
    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        }
        else {
            alert("WebSocket連接沒有建立成功!");
        }
    }
</script>
<form onsubmit="return false;">
    <input type="text" name="message" value="Netty最佳實踐"/>
    <br><br>
    <input type="button" value="發送WebSocket請求消息" onclick="send(this.form.message.value)"/>
    <hr color="blue"/>
    <h3>服務端返回的應答消息</h3>
    <textarea id="responseText" style="width:500px;height:300px;"></textarea>
</form>
</body>
</html>

啟動的時候先啟動 WebSocketServer,然後用瀏覽器打開test.html,點擊 “發送WebSocket請求消息” 就會返回

Netty最佳實踐 , 歡迎使用 Netty WebScoket服務,現在時刻:+new Date();

碼雲地址

GitHub地址

netty websocket