关于java:netty通过websocket实现服务器与客户端的长连接

27次阅读

共计 3812 个字符,预计需要花费 10 分钟才能阅读完成。

server 端代码
import com.chinadaas.bio.chinadaasbio.webSocket.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
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.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class Server {public static void main(String[] args) throws Exception {NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
            serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline pipeline = socketChannel.pipeline();
                    // 因为是基于 http 的 所以应用 http 的编码和解析器
                    pipeline.addLast(new HttpServerCodec());
                    // 是以块形式写,增加 ChunkWriteHandler() 处理器
                    pipeline.addLast(new ChunkedWriteHandler());
                    // http 在传输过程中是分段的,这就是为什么当浏览器发送大量数据的时候,会收回屡次 http 申请
                    pipeline.addLast(new HttpObjectAggregator(8192));
                    // 1:对应 websocket 他的数据是以帧的模式传递
                    // 2: WebSocketServerProtocolHandler 性能是将 http 协定降级为 ws 协定, 放弃一个长连贯
                    pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                    // 增加自定义的 handler
                    pipeline.addLast(new ServerHandler());
                }
            });
            ChannelFuture channelFuture = serverBootstrap.bind(8886).sync();
            channelFuture.channel().closeFuture().sync();} finally {boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();}
    }

}
ServerHandler 代码
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

public class ServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {System.out.println("服务器收到音讯:" + textWebSocketFrame.text());
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("服务器工夫" + LocalDateTime.now() + " " + textWebSocketFrame.text()));

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {System.out.println(ctx.channel().remoteAddress()+"断开了连贯");


    }
}
websocket html 代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    if (window.WebSocket) {socket = new WebSocket("ws://localhost:8886/hello")
        socket.onmessage = function (ev) {var rt = document.getElementById("responseText")
            rt.value = rt.value + "\n" + ev.data;
        }
        socket.onopen = function (ev) {var rt = document.getElementById("responseText")
            rt.value = "连贯开启了...";
        }
        socket.onclose = function (ev) {var rt = document.getElementById("responseText")
            rt.value = rt.value + "\n" + "连贯敞开了";
        }

    } else {alert("以后浏览器不反对 websocket")
    }

    function send(message) {if (!window.socket) {return;}
        if (socket.readyState == WebSocket.OPEN) {socket.send(message);
        } else {alert("连贯没有开启...")
        }
    }


</script>
<form onsubmit="return false">
    <textarea name="message" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="发送音讯" onclick="send(this.form.message.value)"/>
    <textarea id="responseText" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''"/>
</form>

</body>
</html>

欢送大家前来探讨

正文完
 0