netty實現websocket(二)----實例

1 pom文件

本文的例子基於netty4.0。

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

2 服務端開發

websocket服務端的功能如下:服務端對請求的消息進行判斷,如果第一次請求爲http請求,進行握手連接;如果爲合法的websocket,獲取請求的消息文本,在其前面追加字符串”服務器收到並返回:“。
2.1 WebSocketServer啓動類

public class WebSocketServer {
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();
    private final EventLoopGroup bossGroup = new NioEventLoopGroup();

    public void run(){
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("http-codec",new HttpServerCodec());
                    pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
                    pipeline.addLast("http-chunked",new ChunkedWriteHandler());
                    pipeline.addLast("handler",new WebSocketServerHandler());       
                }

            });

        try {
            Channel ch = boot.bind(2048).sync().channel();
            System.out.println("websocket server start at port:2048");
            ch.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
           bossGroup.shutdownGracefully();
           workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {    
       new WebSocketServer().run();
    }

}

備註:本例中默認的開通的端口爲2048,可以自動動態配置

分析:

pipeline.addLast("http-codec",new HttpServerCodec());

上述代碼表示將請求和應答的消息編碼或者解碼爲HTTP消息;

pipeline.addLast("aggregator",new HttpObjectAggregator(65536));

上述代碼表示將HTTP消息的多個部分組合成一條完整的HTTP消息;

pipeline.addLast("http-chunked",new ChunkedWriteHandler());

上述代碼表示向客戶端發送HTML5文件,主要用於支持瀏覽器和服務端進行websocket通信;

pipeline.addLast("handler",new WebSocketServerHandler());

表示增加消息的Handler處理類WebSocketServerHandler。

2.2 WebSocket服務端處理類

在服務端處理類中需要處理兩種類型的消息,一種的HTTP請求,一種是WebSocket請求;因爲WebSocket在建立連接時需要HTTP協議的參與,所有第一次請求消息是由HTTP消息承載。

public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>{

    private  WebSocketServerHandshaker handshaker;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg)
            throws Exception {

        /**
         * HTTP接入,WebSocket第一次連接使用HTTP連接,用於握手
         */
        if(msg instanceof FullHttpRequest){
            handleHttpRequest(ctx, (FullHttpRequest)msg);
        }

        /**
         * Websocket 接入
         */
        else if(msg instanceof WebSocketFrame){
            handlerWebSocketFrame(ctx, (WebSocketFrame)msg);
        }

    }

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

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


    private void handleHttpRequest(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(
                "ws://localhost:2048/ws", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedWebSocketVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    private static 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();
        }
        // 如果是非Keep-Alive,關閉連接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private static boolean isKeepAlive(FullHttpRequest req) {
        return false;
    }

    private void handlerWebSocketFrame(ChannelHandlerContext ctx,
            WebSocketFrame frame) {

        /**
         * 判斷是否關閉鏈路的指令
         */
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(),
                    (CloseWebSocketFrame) frame.retain());
            return;
        }

        /**
         * 判斷是否ping消息
         */
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        /**
         * 本例程僅支持文本消息,不支持二進制消息
         */
        if (frame instanceof BinaryWebSocketFrame) {
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        if(frame instanceof TextWebSocketFrame){
            // 返回應答消息
            String request = ((TextWebSocketFrame) frame).text();
            System.out.println("服務端收到:" + request);
            ctx.channel().write(new TextWebSocketFrame("服務器收到並返回:"+request));
        }

    }
}

3 客戶端頁面

<head>
<title>Netty WebSocket DEMO</title>
</head>
<body>
    <script type="text/javascript">
        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            socket = new WebSocket("ws://localhost:2048/ws");
            socket.onmessage = function(event) {
                var ta = document.getElementById('responseText');
                ta.value = ta.value + '\n' + event.data
            };
            socket.onopen = function(event) {
                var ta = document.getElementById('responseText');
                ta.value = "連接開啓!";
            };
            socket.onclose = function(event) {
                var ta = document.getElementById('responseText');
                ta.value = ta.value + "連接被關閉";
            };
        } else {
            alert("你的瀏覽器不支持!");
        }

        function send(message) {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(message);
            } else {
                alert("連接沒有開啓.");
            }
        }
    </script>
    <form onsubmit="return false;">
        <input type="text" name="message" value="Hello, World!"><input
            type="button" value="發送消息"
            onclick="send(this.form.message.value)">
        <h3>輸出:</h3>
        <textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
        <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空">
    </form>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章