netty+websocket实现数据实时推送(springboot)

以前经常用netty来写TCP链接的处理,然后有些需求就是要求数据实时更新,所以就想到了websocket。

netty实现websockt跟TCP区别不大,主要区别就是配置的解码器和添加关于websocket的东西,业务处理并没有特殊添加。

简单实现

首先引入netty依赖

	
		
		
			io.netty
			netty-all
			4.1.36.Final
		
	

配置NettyServer

package com.home.reptile.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
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.stream.ChunkedWriteHandler;

/**
 * @author wqy
 * @version 1.0
 * @date 2019/8/8 15:39
 */
public class NettyServer {

    private final int port;

    public NettyServer(int port){
        this.port = port;
    }

    public void start() throws Exception{
        EventLoopGroup bossGroup = new NioEventLoopGroup();

        EventLoopGroup group = new NioEventLoopGroup();

        try {


            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG,1024);
            sb.group(group,bossGroup)//绑定线程池
                    .channel(NioServerSocketChannel.class)//指定使用的channel
                    .localAddress(this.port)//绑定监听端口
                    .childHandler(new ChannelInitializer() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("收到新连接");
                            //websocket协议本身就是基于http协议的,所以这边也要使用http编解码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            //以块的方式来写处理器
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws",null,true,65536*10));
                            ch.pipeline().addLast(new MyWebSocketHandler());
                        }

                    });
            //服务器异步创建绑定
            ChannelFuture cf = sb.bind().sync();
            System.out.println(NettyServer.class+" 启动正在监听: "+cf.channel().localAddress());
            //关闭服务器通道
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
            bossGroup.shutdownGracefully().sync();
        }
    }
}

启动nettyserver,开启一个线程,单独启动server

package com.home.reptile.netty;

/**
 * @author wqy
 * @version 1.0
 * @date 2019/8/8 16:06
 */
public class StratNetty implements Runnable{


    @Override
    public void run() {
        try {
            new NettyServer(6655).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

处理业务逻辑和通道管理

package com.home.reptile.netty;

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

import java.util.HashMap;
import java.util.Map;


/**
 * @author wqy
 * @version 1.0
 * @date 2019/8/8 15:59
 */
public class MyWebSocketHandler extends SimpleChannelInboundHandler {

    /**
     * 通道建立调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端建立连接,通道开启!");

        //将链接存入连接池(自定义)
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    /**
     * 通道断开调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接,通道关闭!");
        //添加到channelGroup 通道组
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    /**
     * 通道数据读取
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest,处理参数 by zhengkai.blog.csdn.net
        if (null != msg && msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap=getUrlParams(uri);
            //System.out.println("接收到的参数是:"+JSON.toJSONString(paramMap));
            //如果url包含参数,需要处理
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            }

        }else if(msg instanceof TextWebSocketFrame){
            //正常的TEXT消息类型
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;
            System.out.println("客户端收到服务器数据:" +frame.text());
            sendAllMessage(frame.text());
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

    private void sendAllMessage(String message){
        //收到信息后,群发给所有channel
        MyChannelHandlerPool.channelGroup.writeAndFlush( new TextWebSocketFrame(message));
    }

    private static Map getUrlParams(String url){
        Map map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";")){
            return map;
        }
        if (url.split(";").length > 0){
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr){
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            }
            return  map;

        }else{
            return map;
        }
    }
}

通道连接池

package com.home.reptile.netty;



import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
/**
 * @author wqy
 * @version 1.0
 * @date 2019/8/8 15:59
 */
public class MyChannelHandlerPool {

    public MyChannelHandlerPool(){}

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

}


页面




    
    Netty-Websocket
    






服务端返回的应答消息

controller

@RestController
public class IndexController {
	
	@GetMapping("/index")
	public ModelAndView  index(){
		ModelAndView mav=new ModelAndView("socket");
		mav.addObject("uid", RandomUtil.randomNumbers(6));
		return mav;
	}
	
}

差不多一个简单的例子就实现了

积少成多。

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