netty使用websocket支持长连接

文章目录

  • 前言
  • 一、介绍
  • 二、使用步骤
    • 1.服务端
    • 2.客户端
    • 3.任意浏览器打开html


前言

netty版本4.1.80.Final。


一、介绍

netty使用websocket让服务器和浏览器保持长连接状态。

二、使用步骤

1.服务端

WebSocketServer.java

package netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
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;

/**
 * Create by zjg on 2022/9/25
 */
public class WebSocketServer {
    public static void main(String[] args) {
        run();
    }
    public static void run(){
        NioEventLoopGroup bossGroup = null;
        NioEventLoopGroup workGroup = null;
        try {
            bossGroup=new NioEventLoopGroup();
            workGroup=new NioEventLoopGroup();
            ServerBootstrap serverBootstrap=new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new HttpObjectAggregator(1024));
                            pipeline.addLast(new WebSocketServerProtocolHandler("/websocket"));
                            pipeline.addLast(new WebSocketChannelHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            System.out.println("websocket服务器启动完成");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            System.out.println("websocket服务器已关闭!");
        }
    }
}

WebSocketChannelHandler.java

package netty.websocket;

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

/**
 * Create by zjg on 2022/9/25
 */
public class WebSocketChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        String content= LocalDateTime.now()+ " 服务器响应:"+text;
        channelHandlerContext.writeAndFlush(new TextWebSocketFrame(content));
    }

    @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 {
        ctx.close();
    }
}

2.客户端

websocket.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>websocket测试界面</title>
</head>
<body>
<form onsubmit="return false">
    <textarea id="req" style="width: 300px;height: 200px"></textarea></br>
    <button onclick="send()">发送</button></br>
    <textarea id="res" style="width: 300px;height: 200px"></textarea>
</form>
<script>
    var socket;
    var req= document.getElementById("req");
    var res= document.getElementById("res");
    if(window.WebSocket){
        socket=new WebSocket("ws://localhost:8080/websocket");
        socket.onopen=function (){
            res.value=res.value+"WebSocket开启\n";
        }
        socket.onclose=function (){
            res.value=res.value+"WebSocket关闭\n";
        }
        socket.onmessage=function (response){
            res.value=res.value+response.data+"\n";
        }
    }else{
        alert("当前浏览器不支持websocket!")
    }
    function send(){
        if(!window.socket){
            alert("socket未就绪!")
            return;
        }
        if(req.value==""){
            return false;
        }
        if(socket.readyState==WebSocket.OPEN){
            socket.send(req.value);
            req.value="";
        }else{
            alert("WebSocket未打开!")
        }
    }
</script>
</body>
</html>

3.任意浏览器打开html

netty使用websocket支持长连接_第1张图片


你可能感兴趣的:(java,websocket,java)