如何将请求体以流的形式传递给WebSocket且不损坏数据?
问题描述
我希望将请求体以流的形式获取,并在其上传过程中传递给WebSocket。以下是我当前的实现代码:
InputStream is = request.getInputStream(); int total = 0; int bytes; byte[] buff = new byte[8192]; while ((bytes = is.read(buff)) != -1) { total = total + bytes; this.simpMessagingTemplate.convertAndSend("test", Arrays.toString(buff)); } this.simpMessagingTemplate.convertAndSend("test", "END");
目前发送数据时,我不确定数据是否损坏或重复,但无法解析请求。数据发送完成后我会发送END标识,以便前端知晓可以开始解析数据。
问题分析与解决
- 核心问题:当前代码直接把整个
buff数组转成字符串发送,但read()方法返回的bytes才是实际读取到的有效字节数,缓冲区剩余空间可能残留上次读取的无效数据,导致发送内容包含冗余字节,进而无法正常解析。 - 修复方案:仅发送读取到的有效字节部分,而非整个缓冲区:
- 直接发送有效字节数组:
InputStream is = request.getInputStream(); int total = 0; int bytes; byte[] buff = new byte[8192]; while ((bytes = is.read(buff)) != -1) { total += bytes; // 截取有效字节片段发送 byte[] validBytes = Arrays.copyOf(buff, bytes); this.simpMessagingTemplate.convertAndSend("test", validBytes); } this.simpMessagingTemplate.convertAndSend("test", "END");- 若前端更易处理字符串格式,可转成Base64编码发送:
import java.util.Base64; InputStream is = request.getInputStream(); int total = 0; int bytes; byte[] buff = new byte[8192]; while ((bytes = is.read(buff)) != -1) { total += bytes; byte[] validBytes = Arrays.copyOf(buff, bytes); String base64Str = Base64.getEncoder().encodeToString(validBytes); this.simpMessagingTemplate.convertAndSend("test", base64Str); } this.simpMessagingTemplate.convertAndSend("test", "END"); - 额外注意事项:
- 前端需按接收顺序拼接所有数据片段,直到收到
END标识后再执行解析操作。 - 若传输的是文本数据,需确保前后端使用统一字符编码(如UTF-8),避免出现乱码问题。
- 前端需按接收顺序拼接所有数据片段,直到收到
内容的提问来源于stack exchange,提问作者BoostedAnimal
相关产品推荐
相关产品推荐

