前端websocket使用心得-------二进制数据传输

本文探讨了在前端使用WebSocket进行二进制数据传输,特别是ArrayBuffer的应用。通过WebSocket实现长连接,适用于实时交互场景如聊天。详细介绍了如何初始化WebSocket连接,监听其状态变化,以及使用FileReader读取文件并转化为ArrayBuffer。在发送文件时,需要添加头部信息以便于后台识别请求,通过视图对象处理ArrayBuffer,实现多个视图的拼接,从而完成数据的完整发送。
摘要由CSDN通过智能技术生成

                                    前端websocket使用心得-------二进制数据传输

在由于websocket是长连接,所以在一些业务场景下,前后台的交互使用websocket通讯会比较合适,具体场景不赘述,比如说实时聊天等。

本文主要简述一下前端如何使用websocket。

1、js有H5的window内置对象中有websocket方法,这个 通过new方法可以获取到websocket通讯的客户端。使用如下方法初始化一个websocket连接,获取客户端连接对象。

plugin = new wsSocket('ws://localhost:8000/server');
plugin = new wsSocket('wss://localhost:8000/server');

其中wss为安全连接。这里需要注意,在https的路径下是不可以使用ws连接的(firefox及低版本chrome)。

2、此处列出几个websocket的几个监听方法

onOpen  :监听连接成功

onerror:连接出错

   onClose:连接断开

  onMessage:收

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
netty-websocket-spring-boot-starter是一个基于Netty实现的WebSocket框架,可以方便地在Spring Boot应用中集成WebSocket功能。使用该框架可以快速构建实时通信、消息推送等功能。 下面是一个使用netty-websocket-spring-boot-starter的简单案例: 1. 在pom.xml中添加依赖: ```xml <dependency> <groupId>com.github.wujiuye</groupId> <artifactId>netty-websocket-spring-boot-starter</artifactId> <version>1.0.0.RELEASE</version> </dependency> ``` 2. 编写WebSocket处理器 ```java @ServerEndpoint("/websocket/{userId}") @Component public class WebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); private Session session; private String userId; @OnOpen public void onOpen(Session session, @PathParam("userId") String userId) { this.session = session; this.userId = userId; logger.info("WebSocket连接建立,userId: {}", userId); } @OnMessage public void onMessage(String message) { logger.info("收到来自客户端的消息:{}", message); sendMessage("服务端已收到消息:" + message); } @OnClose public void onClose() { logger.info("WebSocket连接关闭,userId: {}", userId); } @OnError public void onError(Throwable t) { logger.error("WebSocket连接异常,userId: {}", userId, t); } public void sendMessage(String message) { try { this.session.getBasicRemote().sendText(message); } catch (IOException e) { logger.error("发送WebSocket消息失败,userId: {}", userId, e); } } } ``` 3. 配置WebSocket 在配置类中添加@EnableWebSocket注解,启用WebSocket功能,同时,也可以配置WebSocket的一些参数,例如端口号、路径等。 ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/websocket/{userId}") .setAllowedOrigins("*"); } } ``` 4. 测试WebSocket 使用浏览器或WebSocket客户端连接WebSocket服务端,例如:ws://localhost:8080/websocket/123,其中123为userId。 以上就是一个简单的netty-websocket-spring-boot-starter使用案例。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值