Netty學習之路 四 (WebSocket)

如果覺得還可以 記得關注一下公衆號哦!一起交流學習!
在這裏插入圖片描述

5.WebSocket

5.1服務端代碼編寫

自定義處理器 編寫

package com.demo.netty.fifthexample.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**
 * 泛型證明這個WebSocket是處理文本類型的
 */
public class MyServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    /**
     * 消息內容
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到消息"+msg.text());
        ctx.writeAndFlush(new TextWebSocketFrame("人間不值得"+ LocalDateTime.now()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("添加客戶端"+ctx.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("刪除客戶端"+ctx.channel().id().asLongText());
    }

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

自定義初始化器編寫

package com.demo.netty.fifthexample.server;

import io.netty.channel.ChannelHandler;
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 MyServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //HTTP編解碼器
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        //Netty 的Http請求是分段的   這個是將分段聚合起來
        pipeline.addLast(new HttpObjectAggregator(8192));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new MyServerHandler());
    }
}

自定義服務器編寫

package com.demo.netty.fifthexample.server;

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.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class MyServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new MyServerChannelInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}

WebSocket 頁面編寫

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script type="text/javascript">
        var socket;
        if(window.WebSocket){
            socket = new WebSocket("ws://localhost:8899/ws");
            socket.onmessage = function (ev) {
                var ta = document.getElementById("responseText")
                ta.value = ta.value + "\n" +ev.data;
            }
            socket.onopen = function (ev) {
                var tar = document.getElementById("responseText")
                tar.value = "連接開啓";
            }
            socket.onclose = function (ev) {
                var tar = document.getElementById("responseText")
                tar.value += "\n連接關閉";
            }
        }else{
            alert("瀏覽器不支持  告辭")
        }


        function send(msg) {
            if(!window.WebSocket){
                return;
            }
            if(socket.readyState == WebSocket.OPEN){
                socket.send(msg);
            }else{
                alert("連接沒有開始")
            }
        }
    </script>

    <form onsubmit="return false">
        <textarea name = "message" style="width: 500px;height: 200px"></textarea>
        <input type="button" value="發送數據" onclick="send(this.form.message.value)"/>
        <h3>服務端輸出</h3>
        <textarea id="responseText" style="width: 500px;height: 200px"></textarea>
        <input type="button" onclick="javascript: document.getElementById('responseText').value=''" value="清空"/>
    </form>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章