时间:2018年04月11日星期三
说明:本文部份内容均来自慕课网。@慕课网:https://www.imooc.com
教学源码:https://github.com/zccodere/s...
学习源码:https://github.com/zccodere/s...javascript
什么是Nettyhtml
Netty使用场景java
课程提纲git
课程要求github
BIO通讯web
BIO通讯模型apache
伪异步IO通讯编程
伪异步IO通讯模型bootstrap
NIO通讯浏览器
AIO通讯
四种IO对比
原生NIO的缺陷
Netty的优点
什么是WebSocket
WebSocket的优势
WebSocket创建链接
WebSocket生命周期
WebSocket关闭链接
基于Netty实现WebSocket通讯案例
功能介绍
代码编写
1.建立名为netty-websocket的maven工程pom以下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.myimooc</groupId> <artifactId>netty-websocket</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
2.编写NettyConfig类
package com.myimooc.netty.websocket; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.util.concurrent.GlobalEventExecutor; /** * <br> * 标题: Netty 全局配置类<br> * 描述: 存储整个工程的全局配置<br> * * @author zc * @date 2018/04/11 */ public class NettyConfig { /** * 存储每个客户端接入进来时的 Channel */ public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); }
3.编写MyWebSocketHandler类
package com.myimooc.netty.websocket; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.websocketx.*; import io.netty.util.CharsetUtil; import java.util.Date; /** * <br> * 标题: 处理客户端WebSocket请求的核心业务处理类<br> * 描述: 接收/处理/响应 客户端websocket请求的核心业务处理类<br> * * @author zc * @date 2018/04/11 */ public class MyWebSocketHandler extends SimpleChannelInboundHandler<Object> { private WebSocketServerHandshaker handshaker; private static final String WEB_SOCKET_URL = "ws://localhost:8888/websocket"; /** * 服务端处理客户端websocket请求的核心方法 */ @Override protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { // 处理客户端向服务端发起http握手请求的业务 FullHttpRequest request = (FullHttpRequest) msg; this.handHttpRequest(ctx, request); } else if (msg instanceof WebSocketFrame) { // 处理websocket链接的业务 WebSocketFrame frame = (WebSocketFrame) msg; this.handWebSocketFrame(ctx, frame); } } /** * 处理客户端与服务端以前的websocket业务 */ private void handWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame){ // 若是是关闭websocket的指令 handshaker.close(ctx.channel(),(CloseWebSocketFrame)frame.retain()); } if (frame instanceof PingWebSocketFrame){ // 若是是ping消息 ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)){ // 若是不是文本消息,则抛出异常 System.out.println("目前暂不支持二进制消息"); throw new RuntimeException("【"+this.getClass().getName()+"】不支持二进制消息"); } // 获取客户端向服务端发送的文本消息 String request = ((TextWebSocketFrame) frame).text(); System.out.println("服务端收到客户端的消息=====>>>" + request); // 将客户端发给服务端的消息返回给客户端 TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString() + ctx.channel().id() + "====>>>" + request); // 群发,服务端向每一个链接上来的客户端群发消息 NettyConfig.group.writeAndFlush(tws); } /** * 处理客户端向服务端发起http握手请求的业务 */ private void handHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) { if (!request.getDecoderResult().isSuccess() || !("websocket").equals(request.headers().get("Upgrade"))) { // 不是websocket握手请求时 this.sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST)); return; } WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(WEB_SOCKET_URL, null, false); handshaker = wsFactory.newHandshaker(request); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), request); } } /** * 服务端向客户端响应消息 */ private void sendHttpResponse(ChannelHandlerContext ctc, FullHttpMessage request, DefaultFullHttpResponse response) { if (response.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(response.getStatus().toString(), CharsetUtil.UTF_8); response.content().writeBytes(buf); buf.release(); } // 服务端向客户端发送数据 ChannelFuture future = ctc.channel().writeAndFlush(response); if (response.getStatus().code() != 200) { future.addListener(ChannelFutureListener.CLOSE); } } /** * 工程出现异常时调用 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } /** * 客户端与服务端建立链接时调用 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { NettyConfig.group.add(ctx.channel()); System.out.println("客户端与服务端链接开启..."); } /** * 客户端与服务端断开链接时调用 */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { NettyConfig.group.remove(ctx.channel()); System.out.println("客户端与服务端链接关闭..."); } /** * 服务端接收客户端发送过来的数据结束以后调用 */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }
4.编写MyWebSocketChannelHandler类
package com.myimooc.netty.websocket; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInitializer; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.stream.ChunkedWriteHandler; /** * <br> * 标题: 初始化链接时的各个组件<br> * 描述: 初始化链接时的各个组件<br> * * @author zc * @date 2018/04/11 */ public class MyWebSocketChannelHandler extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { // 将请求和应答消息解码为HTTP消息 ch.pipeline().addLast("http-codec",new HttpServerCodec()); // 将HTTP消息的多个部分合成一条完整的HTTP消息 ch.pipeline().addLast("aggregator",new HttpObjectAggregator(65536)); // 向客户端发送HTML5文件 ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("handler",new MyWebSocketHandler()); } }
5.编写AppStart类
package com.myimooc.netty.websocket; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; /** * <br> * 标题: 程序入口<br> * 描述: 启动应用<br> * * @author zc * @date 2018/04/11 */ public class AppStart { public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup,workGroup); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.childHandler(new MyWebSocketChannelHandler()); System.out.println("服务端开启等待客户端链接..."); Channel channel = serverBootstrap.bind(8888).sync().channel(); channel.closeFuture().sync(); }catch (Exception e){ e.printStackTrace(); }finally { // 优雅的退出程序 bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } }
6.编写websocket.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="content-type" content="text/html"/> <title>WebSocket客户端</title> <script type="text/javascript"> var socket; if (!window.WebSocket) { window.WebSocket = window.MozWebSocket; } if (window.WebSocket) { socket = new WebSocket("ws://localhost:8888/websocket"); socket.onmessage = function (event) { var ta = document.getElementById("responseContent"); ta.value += event.data + "\r\n"; }; socket.onopen = function (event) { var ta = document.getElementById("responseContent"); ta.value = "您当前的浏览器支持 WebSocket,请进行后续操做\r\n"; }; socket.onclose = function (event) { var ta = document.getElementById("responseContent"); ta.value = ""; ta.value = "WebSocket 链接已近关闭\r\n"; }; } else { alert("您的浏览器不支持 WebSocket"); } function send(msg) { if (!window.WebSocket) { return; } if (socket.readyState == WebSocket.OPEN) { socket.send(msg); } else { alert("WebSocket链接没有创建成功"); } } </script> </head> <body> <form onSubmit="return false;"> <input type="text" name="msg" value=""/> <br/> <br/> <input type="button" value="发送WebSocket请求消息" onclick="send(this.form.msg.value)"/> <hr color="red"/> <h2>客户端接收到服务端返回的应答消息</h2> <textarea id="responseContent" style="width: 1024px;height: 300px"></textarea> </form> </body> </html>
课程总结