十二.Netty之WebSocket

1.WebSocket简介

在Http1.0和Http1.1协议中,我们要实现服务端主动的发送消息到网页或者APP上,是比较困难的,尤其是现在IM(即时通信)几乎是很多APP都需要实现的功能,我们往往采用一种轮询的方式让终端去请求服务器获取对应的数据,相信很多做过IM通信的朋友应该深有感触,其实大多数的轮询都是无效的(即没有获得到任何的数据);另外一个方面,每一次轮询都是一个完整的Http请求,而根据Http协议,每一次请求都要在Header中携带大量的参数,这无疑对带宽也是一种极大的消耗。
html5的诞生为我们带来的WebSocket,WebSocket是基于Http协议的一种长连接协议,有了这种协议,我们就可以实现服务端主动往客户端发送消息的功能。

2.代码示例

WebsocketServer

public class WebsocketServer {
  public static void main(String[] args) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
      ServerBootstrap serverBootstrap = new ServerBootstrap();
      serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
          .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new WebSocketChannelInitializer());

      ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
      channelFuture.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
}

WebSocketChannelInitializer

public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

  @Override
  protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    //HttpServerCodec: 针对http协议进行编解码
    pipeline.addLast("httpServerCodec", new HttpServerCodec());
    //ChunkedWriteHandler分块写处理,文件过大会将内存撑爆
    pipeline.addLast("chunkedWriteHandler", new ChunkedWriteHandler());
    /**
     1. http数据在传输过程中是分段, HttpObjectAggregator ,就是可以将多个段聚合
     2. 这就就是为什么,当浏览器发送大量数据时,就会发出多次http请求
     */
    pipeline.addLast("httpObjectAggregator", new HttpObjectAggregator(8192));

    /**
     1. 对应websocket ,它的数据是以 帧(frame) 形式传递
     2. 可以看到WebSocketFrame 下面有六个子类
     3. 浏览器请求时 ws://localhost:9999/ws表示请求的uri
     4. WebSocketServerProtocolHandler 核心功能是将 http协议升级为 ws协议 , 保持长连接
     5. 是通过一个 状态码 101
     */
    pipeline.addLast("webSocketServerProtocolHandler", new WebSocketServerProtocolHandler("/ws"));

    pipeline.addLast("webSocketHandler", new WebSocketHandler());
  }
}

WebSocketHandler

/**
 * 这里 TextWebSocketFrame 类型,表示一个文本帧(frame)
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
    System.out.println("服务器收到消息 " + msg.text());
    Date date = new Date(); //获取当前的系统时间。
    //回复消息
    ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间" + dateFormat.format(date) + " " + msg.text()));
  }

  //当web客户端连接后, 触发方法
  @Override
  public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    //id 表示唯一的值,LongText 是唯一的 ShortText 不是唯一
    System.out.println("handlerAdded 被调用" + ctx.channel().id().asLongText());
    System.out.println("handlerAdded 被调用" + ctx.channel().id().asShortText());
  }

  @Override
  public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    System.out.println("用户下线: " + ctx.channel().id().asLongText());
  }

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

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    //判断当前浏览器是否支持websocket
    if (window.WebSocket) {
        //go on
        socket = new WebSocket("ws://localhost:9999/ws");
        //相当于channelReado, ev 收到服务器端回送的消息
        socket.onmessage = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + ev.data;
        }

        //相当于连接开启(感知到连接开启)
        socket.onopen = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = "连接开启了.."
        }

        //相当于连接关闭(感知到连接关闭)
        socket.onclose = function (ev) {

            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + "连接关闭了.."
        }
    } else {
        alert("当前浏览器不支持websocket")
    }

    //发送消息到服务器
    function send(message) {
        if (!window.socket) { //先判断socket是否创建好
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            //通过socket 发送消息
            socket.send(message)
        } else {
            alert("连接没有开启");
        }
    }
</script>
<form onsubmit="return false">
    <textarea name="message" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="发生消息" onclick="send(this.form.message.value)">
    <textarea id="responseText" style="height: 300px; width: 300px"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>

效果图
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netty是一个基于Java的网络编程框架,它提供了一种简单且高性能的方式来实现WebSocket协议。 要使用Netty实现WebSocket,可以按照以下步骤进行操作: 1. 创建一个新的Netty项目,并添加Netty的依赖。 2. 创建一个WebSocket服务器类,该类需要继承自`io.netty.channel.SimpleChannelInboundHandler`。 3. 在服务器类中,重写`channelRead0`方法,处理接收到的WebSocket消息。 4. 在服务器类中,重写`channelActive`和`channelInactive`方法,处理WebSocket连接的打开和关闭事件。 5. 在服务器类中,重写`exceptionCaught`方法,处理异常情况。 6. 创建一个启动类,在其中创建并配置一个`io.netty.bootstrap.ServerBootstrap`实例。 7. 在启动类中,绑定服务器端口并启动服务器。 下面是一个简单的示例代码,演示了如何使用Netty实现WebSocket服务器: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; 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.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; public class WebSocketServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast(new HttpObjectAggregator(65536)); ch.pipeline().addLast(new WebSocketServerProtocolHandler("/websocket")); ch.pipeline().addLast(new WebSocketServerHandler()); } }); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` 在上面的代码中,`WebSocketServerHandler`是自定义的处理器,用于处理WebSocket消息。你可以根据自己的需求来实现该处理器。 请注意,这只是一个简单的示例,实际的WebSocket服务器可能需要更复杂的处理逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值