扩展篇】四. WebSocket简单介绍和使用

本文详细介绍了WebSocket协议,探讨其解决http协议的局限性,实现服务端与客户端的双向通信。通过Netty搭建WebSocket服务器,涵盖项目搭建、编码解码、心跳检测等关键环节。


中国加油,武汉加油!

篇幅较长,请配合目录观看

项目准备

  1. 本案例基于 扩展篇】三. Netty基本介绍及使用

1. 什么是WebSocket

  1. http协议只能由客户端发起,服务端无法直接进行推送。这就导致了如果服务端有持续变化,客户端想要获知就很麻烦。
  2. WebSocket协议就是为了解决这个给问题应运而生。通过该协议,服务端和客户端都可以主动推送信息。
  3. 推送的消息可以是文本也可以是二进制数据。而且没有同源策略的限制,不存在跨域问题。
  4. 协议的标识是ws。
  5. WebStocket是H5之后提供的一种网络通讯技术,属于应用层协议。基于TCP传输协议,并复用HTTP的握手通道。

2. WebSocket帧

2.1 数据帧 – 用来传递数据

  1. TextWebSocketFrame 文本帧
  2. BinaryWebSocketFrame 二进制帧

2.2 状态帧 – 用来检测心跳

  1. PingWebSocketFrame ping帧
  2. PongWebSocketFrame pong帧
  3. CloseWebSocketFrame 关闭帧

3. 使用Netty搭建WebSocket服务器

3.1 新建项目web-socket-demo(maven)

3.2 导包

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

3.3 编写Handler

package com.wpj;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketChannelHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{
   
   
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
   
   
        System.out.println("读取客户端的内容:"+textWebSocketFrame.text());
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
   
   
        System.out.println("新客户端连接。。。");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
   
   
        System.out.println("客户断开连接。。。");
    }
}

3.4 编写服务端

package com.wpj;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
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) {
   
   
        try {
   
   
            EventLoopGroup master = new NioEventLoopGroup();
            EventLoopGroup slave = new NioEventLoopGroup();

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(master, slave);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值