使用netty开发WebSocket服务

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;


import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class WebSocketServer {
    public static void main(String... args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch)
                                throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("http-codec", new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                            ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                            pipeline.addLast("handler", new WebSocketServerHandler());
                        }
                    });

            Channel ch = b.bind(8080).sync().channel();
            System.out.println("Web socket server started at port " + 8080
                    + '.');
            System.out
                    .println("Open your browser and navigate to http://localhost:"
                            + 8080 + '/');

            ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
        private WebSocketServerHandshaker handshaker;

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            // http请求,建立握手连接
            if (msg instanceof FullHttpRequest) {
                handleHttpRequest(ctx, (FullHttpRequest) msg);
            } else if (msg instanceof WebSocketFrame) {
                handleWebSocketFrame(ctx, (WebSocketFrame) msg);
            }
        }

        private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
            // 关闭链路的控制消息
            if (frame instanceof CloseWebSocketFrame) {
                System.out.println("收到关闭请求");
                handshaker.close(ctx.channel(), ((CloseWebSocketFrame) frame).retain());
                return;
            }
            // 维持链路的ping消息
            if (frame instanceof PingWebSocketFrame) {
                System.out.println("收到ping");
                ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
                return;
            }
            // 通信双方只使用文本
            if (!(frame instanceof TextWebSocketFrame)) {
                throw new UnsupportedOperationException(String.format(
                        "%s frame types not supported", frame.getClass().getName()));
            }

            // 客户端发过了的消息
            String request = ((TextWebSocketFrame) frame).text();
            // 服务端返回客户端发过了的消息 + 当前时间
            ctx.channel().write(new TextWebSocketFrame(request
                    + " , 欢迎使用Netty WebSocket服务,现在时刻:" + new java.util.Date().toString()));

        }

        private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
            // 根据请求头Upgrade字段判断是不是websocket
            if (!req.decoderResult().isSuccess() || !"websocket".equals(req.headers().get("Upgrade"))) {
                // 400
                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
                return;
            }
            // 握手工厂
            WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                    "ws://localhost:8080/websocket", null, false);
            // 将websocket相关的编/解码类动态添加到ChannelPipeline
            handshaker = wsFactory.newHandshaker(req);
            if (handshaker == null) {
                WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
            } else {
                System.out.println("进行握手");
                // 握手
                handshaker.handshake(ctx.channel(), req);
            }
        }


        private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, DefaultFullHttpResponse res) {
            if (res.status().code() != 200) {
                ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
                res.content().writeBytes(buf);
                buf.release();
                HttpUtil.setContentLength(res, res.content().readableBytes());
            }
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
}

页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
Netty WebSocket 时间服务器
</head>
<br>
<body>
<br>
<script type="text/javascript">
var socket;
if (!window.WebSocket) 
{
	window.WebSocket = window.MozWebSocket;
}
if (window.WebSocket) {
	socket = new WebSocket("ws://localhost:8080/websocket");
	socket.onmessage = function(event) {
		var ta = document.getElementById('responseText');
		ta.value="";
		ta.value = event.data
	};
	socket.onopen = function(event) {
		var ta = document.getElementById('responseText');
		ta.value = "打开WebSocket服务正常,浏览器支持WebSocket!";
	};
	socket.onclose = function(event) {
		var ta = document.getElementById('responseText');
		ta.value = "";
		ta.value = "WebSocket 关闭!"; 
	};
}
else
	{
	alert("抱歉,您的浏览器不支持WebSocket协议!");
	}

function send(message) {
	if (!window.WebSocket) { return; }
	if (socket.readyState == WebSocket.OPEN) {
		socket.send(message);
	}
	else
		{
		  alert("WebSocket连接没有建立成功!");
		}
}
</script>
<form onsubmit="return false;">
<input type="text" name="message" value="请求时间"/>
<br><br>
<input type="button" value="发送WebSocket请求消息" onclick="send(this.form.message.value)"/>
<hr color="blue"/>
<h3>服务端返回的应答消息</h3>
<textarea id="responseText" style="width:500px;height:300px;"></textarea>
</form>
</body>
</html>
posted @ 2021-09-28 16:44  fly_bk  阅读(110)  评论(0)    收藏  举报