|
@@ -4,6 +4,8 @@ import io.netty.buffer.ByteBuf;
|
|
|
import io.netty.buffer.Unpooled;
|
|
|
import io.netty.channel.*;
|
|
|
import io.netty.handler.codec.http.*;
|
|
|
+import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
|
|
|
+import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
|
|
|
import io.netty.handler.ssl.SslHandler;
|
|
|
import io.netty.util.CharsetUtil;
|
|
|
|
|
@@ -33,6 +35,11 @@ public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullH
|
|
|
|
|
|
@Override
|
|
|
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
|
|
|
+
|
|
|
+ if (updateProtocol(ctx, req)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
// Handle a bad request.
|
|
|
if (!req.decoderResult().isSuccess()) {
|
|
|
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
|
|
@@ -60,6 +67,37 @@ public class WebSocketIndexPageHandler extends SimpleChannelInboundHandler<FullH
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 协议升级
|
|
|
+ * WebSocket是一种全新的协议,不属于http无状态协议,协议名为"ws",这意味着一个websocket连接地址会是这样的写法:
|
|
|
+ * ws://127.0.0.1:8080/websocket。ws不是http,所以传统的web服务器不一定支持,需要服务器与浏览器同时支持, WebSocket才能正常运行,目前大部分浏览器都支持Websocket。
|
|
|
+ * WebSocketServerHandshaker 服务器端Web套接字打开和关闭握手基类
|
|
|
+ * WebSocketServerHandshakerFactory 自动检测正在使用的网络套接字协议的版本,并创建一个新的合适的 WebSocketServerHandshaker。
|
|
|
+ *
|
|
|
+ * @param ctx
|
|
|
+ * @param req
|
|
|
+ * @return
|
|
|
+ */
|
|
|
+ private boolean updateProtocol(ChannelHandlerContext ctx, FullHttpRequest req) {
|
|
|
+ if ("websocket".equals(req.headers().get("Upgrade"))) {
|
|
|
+ WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://localhost:9011/websocket", null, false);
|
|
|
+ //创建一个握手协议
|
|
|
+ WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
|
|
|
+ if (handshaker == null) {
|
|
|
+ /*
|
|
|
+ Return that we need cannot not support the web socket version
|
|
|
+ 返回不支持websocket 版本
|
|
|
+ */
|
|
|
+ WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
|
|
|
+ } else {
|
|
|
+ //开始握手
|
|
|
+ handshaker.handshake(ctx.channel(), req);
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 返回http消息
|
|
|
*
|