netty实现websocket(二)----实例

本文通过 Netty 4.0 框架实现了一个 WebSocket 服务端,详细介绍了服务端如何处理 HTTP 请求和 WebSocket 请求,并提供了客户端 JavaScript 页面的实现,实现了服务端与客户端之间的实时通信。
摘要由CSDN通过智能技术生成

1 pom文件

本文的例子基于netty4.0。

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.0.24.Final</version>
        </dependency>

2 服务端开发

websocket服务端的功能如下:服务端对请求的消息进行判断,如果第一次请求为http请求,进行握手连接;如果为合法的websocket,获取请求的消息文本,在其前面追加字符串”服务器收到并返回:“。
2.1 WebSocketServer启动类

public class WebSocketServer {
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();
    private final EventLoopGroup bossGroup = new NioEventLoopGroup();

    public void run(){
        ServerBootstrap boot = new ServerBootstrap();
        boot.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {

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

            });

        try {
            Channel ch = boot.bind(2048).sync().channel();
            System.out.println("websocket server start at port:2048");
            ch.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
           bossGroup.shutdownGracefully();
           workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {    
       new WebSocketServer().run();
    }

}

备注:本例中默认的开通的端口为2048,可以自动动态配置

分析:

pipeline.addLast("http-codec",new HttpServerCodec());

上述代码表示将请求和应答的消息编码或者解码为HTTP消息;

pipeline.addLast("aggregator",new HttpObjectAggregator(65536));

上述代码表示将HTTP消息的多个部分组合成一条完整的HTTP消息;

pipeline.addLast("http-chunked",new ChunkedWriteHandler());

上述代码表示向客户端发送HTML5文件,主要用于支持浏览器和服务端进行websocket通信;

pipeline.addLast("handler",new WebSocketServerHandler());

表示增加消息的Handler处理类WebSocketServerHandler。

2.2 WebSocket服务端处理类

在服务端处理类中需要处理两种类型的消息,一种的HTTP请求,一种是WebSocket请求;因为WebSocket在建立连接时需要HTTP协议的参与,所有第一次请求消息是由HTTP消息承载。

public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>{

    private  WebSocketServerHandshaker handshaker;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg)
            throws Exception {

        /**
         * HTTP接入,WebSocket第一次连接使用HTTP连接,用于握手
         */
        if(msg instanceof FullHttpRequest){
            handleHttpRequest(ctx, (FullHttpRequest)msg);
        }

        /**
         * Websocket 接入
         */
        else if(msg instanceof WebSocketFrame){
            handlerWebSocketFrame(ctx, (WebSocketFrame)msg);
        }

    }

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

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


    private void handleHttpRequest(ChannelHandlerContext ctx,FullHttpRequest req){
        if (!req.getDecoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://localhost:2048/ws", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedWebSocketVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx,
            FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        // 如果是非Keep-Alive,关闭连接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    private static boolean isKeepAlive(FullHttpRequest req) {
        return false;
    }

    private void handlerWebSocketFrame(ChannelHandlerContext ctx,
            WebSocketFrame frame) {

        /**
         * 判断是否关闭链路的指令
         */
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(),
                    (CloseWebSocketFrame) frame.retain());
            return;
        }

        /**
         * 判断是否ping消息
         */
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        /**
         * 本例程仅支持文本消息,不支持二进制消息
         */
        if (frame instanceof BinaryWebSocketFrame) {
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        if(frame instanceof TextWebSocketFrame){
            // 返回应答消息
            String request = ((TextWebSocketFrame) frame).text();
            System.out.println("服务端收到:" + request);
            ctx.channel().write(new TextWebSocketFrame("服务器收到并返回:"+request));
        }

    }
}

3 客户端页面

<head>
<title>Netty WebSocket DEMO</title>
</head>
<body>
    <script type="text/javascript">
        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            socket = new WebSocket("ws://localhost:2048/ws");
            socket.onmessage = function(event) {
                var ta = document.getElementById('responseText');
                ta.value = ta.value + '\n' + event.data
            };
            socket.onopen = function(event) {
                var ta = document.getElementById('responseText');
                ta.value = "连接开启!";
            };
            socket.onclose = function(event) {
                var ta = document.getElementById('responseText');
                ta.value = ta.value + "连接被关闭";
            };
        } else {
            alert("你的浏览器不支持!");
        }

        function send(message) {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(message);
            } else {
                alert("连接没有开启.");
            }
        }
    </script>
    <form onsubmit="return false;">
        <input type="text" name="message" value="Hello, World!"><input
            type="button" value="发送消息"
            onclick="send(this.form.message.value)">
        <h3>输出:</h3>
        <textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
        <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空">
    </form>
</body>
</html>
### 使用 Netty WebSocket 实现 SSL 安全通信 在 Spring Boot 中配置基于 NettyWebSocket 并启用 SSL 可以为应用程序提供安全的 Web 套接字连接。以下是具体方法: #### 配置 Maven 或 Gradle 依赖项 为了支持 WebSocket SSL 功能,在 `pom.xml` 文件中添加必要的依赖关系[^1]: 对于 Maven 用户: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- 添加对 Reactor Netty (HTTP/2, WebSocket over TLS) 支持 --> <dependency> <groupId>io.projectreactor.netty</groupId> <artifactId>reactor-netty-http</artifactId> </dependency> <!-- JSR 305 是用于验证注解的支持库 --> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> </dependency> ``` 对于 Gradle 用户,则应在 build.gradle 文件内加入相应条目。 #### 启用 HTTPS 协议并加载证书文件 创建自定义嵌入式服务器工厂来设置 SslContext: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class ServerConfig { @Bean public ReactiveWebServerFactory reactiveWebServerFactory() { NettyReactiveWebServerFactory factory = new NettyReactiveWebServerFactory(); try { SslContext sslContext = SslContextBuilder.forServer( new File("/path/to/cert.pem"), new File("/path/to/key.pkcs8") ).build(); factory.setSslContext(sslContext); return factory; } catch (Exception e) { throw new RuntimeException(e); } } } ``` 这段代码片段展示了如何通过指定路径下的 PEM 格式的公钥认证书以及 PKCS#8 私钥文件构建 SslContext 对象,并将其应用于 Netty 服务器实例上。 #### 创建 WebSocket 控制器类处理消息事件 编写一个简单的控制器用来接收客户端发送过来的消息并向其广播回复信息: ```java @Controller public class EchoWebSocketHandler extends TextWebSocketHandler { private final SimpMessagingTemplate messagingTemplate; @Autowired public EchoWebSocketHandler(SimpMessagingTemplate messagingTemplate){ this.messagingTemplate=messagingTemplate; } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message)throws Exception{ String payload=message.getPayload(); System.out.println("Received from client:"+payload); // 将收到的信息转发给所有已订阅 /topic/greetings 路径下主题的客户终端设备 messagingTemplate.convertAndSend("/topic/greetings", "Echo:" + payload); } } ``` 此部分实现了基本回声功能,即每当有新消息到达时就立即返回相同的内容作为响应。 #### 注册 WebSocket 映射路由规则 最后一步是在应用上下文中注册上述处理器所对应的 URL 地址模式匹配规则: ```java @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS().setClientLibraryUrl("//cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"); } @Override public void configureMessageBroker(MessageBrokerRegistry configurer) { configurer.enableSimpleBroker("/topic"); // 订阅者监听前缀 configurer.setApplicationDestinationPrefixes("/app"); // 发布者请求前缀 } } ``` 以上就是整个过程的大致描述,其中包含了从引入所需组件到完成实际业务逻辑的具体操作指南。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值