文章目录
参考博客0
一、webSocket的作用
1)通知功能:
2)数据收集:
3)加密 && 认证:
4)反向控制钩子:
二、webSocket的优缺点
1、优点
1、websocket则允许我们在一条ws连接上同时并发多个请求,即在A请求发出后A响应还未到达,就可以继续发出B请求。由于TCP的慢启动特性(新连接速度上来是需要时间的),以及连接本身的握手损耗,都使得websocket协议的这一特性有很大的效率提升。
2、webSocket的复用性可以利用上一条请求内容
3、websocket支持服务器推送消息,这带来了及时消息通知的更好体验,也是ajax请求无法达到的。
2、缺点
1、服务器长期维护长连接需要一定的成本
2、各个浏览器支持程度不一
3、websocket 是长连接,受网络限制比较大,需要处理好重连,比如用户进电梯或电信用户打个电话网断了,这时候就需要重连
3、webSocket与Http协议的异同
三、webSocket重要步骤
步骤:
1.后端
a.搭建服务器和处理器
2.前端
a.判断是否支持webSocket
b.创建webSocket对象设置参数uri
c.设计发送(send)、接收和显示(show)消息方法
d.心跳机制:确保客户端或服务器活着
e.重连机制:当客户端或服务器恢复后能够重新连上
1、后端
1.1、webSocket服务器搭建
- 导入依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.77.Final</version>
</dependency>
- 服务类代码实现
package com.wxl.websocket;
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 salve=new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(master,salve);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
//http编码器
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(1024*10));
pipeline.addLast(new WebSocketServerProtocolHandler("/"));//此处设置映射路径
//自定义客户端处理器
pipeline.addLast(new WebSocketServerHandler());
}
});
ChannelFuture channelFuture = bootstrap.bind(8081);
channelFuture.sync();
System.out.println("服务端启动成功。。。。");