方式:
- Ajax轮询:前端使用ajax不断访问后台(异步);一般适用于小项目或者后台管理;
- Long pull:阻塞式请求;如果服务器不响应便会阻塞;
- webSocket:不同于上面两种方式,webSocket使用了http协议完成了一小部分的握手,是一种持久化协议;只需要建立一次请求,服务端就可以推送到客户端;
实现步骤:
- 后台代码
- 建立一个package命名为webSocket,在webSocket包中建立server启动类WSServer.java;
import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class WSServer { public static void main(String[] args) throws Exception { NioEventLoopGroup mainGroup = new NioEventLoopGroup(); NioEventLoopGroup subGroup = new NioEventLoopGroup(); try { ServerBootstrap server = new ServerBootstrap(); server.group(mainGroup,subGroup) .channel(NioServerSocketChannel.class) .childHandler(null); ChannelFuture future = server.bind(8088).sync(); future.channel().closeFuture().sync(); } finally { mainGroup.shutdownGracefully(); subGroup.shutdownGracefully(); } } }
- 在webSocket包中建立server初始化类WSServerInitializer.java;
package com.gyzl.netty.webSocket; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipe
- 建立一个package命名为webSocket,在webSocket包中建立server启动类WSServer.java;