websocket文字消息传递直接通过String接收即可,但是保不齐你想给朋友发送一个照片或者语音,怎么办呢?
本文在消息传递的基础上进行升级,添加文件消息推送的简单实现,需要的童鞋可以做个参考。
文字消息推送可以参考【下面有源码链接】:websocket点对点消息推送 - 简书
实现思路:
- 前端上传文件
- websocket将二进制的文件流推送给接收方
最终效果
前端实现
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>socket消息推送</title>
<div th:replace="~{common/links::header}"></div>
<div th:replace="~{common/script::js_footer}"></div>
</head>
<body>
<div class="layui-bg-gray" style="padding: 16px;">
<div class="layui-row layui-col-space15">
<div class="layui-col-md6 layui-col-md-offset3">
<div class="layui-card">
<div class="layui-card-header">消息发送面板(发送人:<span id="sender"></span>)</div>
<div class="layui-card-body">
<form class="layui-form layui-form-pane" id="searchForm">
<div class="layui-form-item" pane>
<label class="layui-form-label">发送给</label>
<div class="layui-input-block">
<input type="radio" name="receiveUserId" value="路飞" title="路飞" checked>
<input type="radio" name="receiveUserId" value="索隆" title="索隆">
<input type="radio" name="receiveUserId" value="艾斯" title="艾斯">
</div>
</div>
<div class="layui-form-item layui-form-text">
<div class="layui-input-block">
<textarea placeholder="请输入需要发送的消息" class="layui-textarea" name="msg" ></textarea>
</div>
</div>
<div class="layui-form-item layui-form-text">
<div class="layui-input-block">
<button type="button" class="layui-btn file_msg layui-bg-blue" lay-options="{accept: 'file'}">
<i class="layui-icon layui-icon-upload"></i>
上传文件
</button>
</div>
</div>
<div class="layui-form-item">
<button class="layui-btn" lay-submit="" lay-filter="add" >发送消息</button>
<!-- <button type="button" class="layui-btn" id="ID-upload-file-action">发送文件</button>-->
</div>
</form>
</div>
</div>
</div>
<div class="layui-col-md6 layui-col-md-offset3">
<div class="layui-card">
<div class="layui-card-header">消息接收面板</div>
<div class="layui-card-body">
<span id="content"></span>
<img src="" id="imgMsg" style="width: 150px;height: 150px;display: none">
</div>
</div>
</div>
</div>
</div>
</body>
<script th:inline="javascript">
layui.use('form', function () {
var $ = layui.jquery,form = layui.form,upload = layui.upload;
const urlParams = new URLSearchParams(window.location.search);
const sendUserId = urlParams.get('sendUserId');
$("#sender").html(sendUserId)
form.on('submit(add)', function (data) {
let param = {userId:sendUserId}
Object.assign(param,data.field);
Common.ajaxFormSubmit('/websocket/send', param, function (data) {
layer.msg('消息已发送')
});
return false;
});
// 渲染
upload.render({
elem: '.file_msg', // 绑定多个元素
url: '/websocket/byteBuffer', // 此处配置你自己的上传接口即可
data: {userId:sendUserId,receiveUserId:function () {
return $("input[name='receiveUserId']:checked").val()
}},
accept: 'file', // 普通文件
// bindAction: '#ID-upload-file-action',
done: function(res){
layer.msg('上传成功');
console.log(res);
}
});
let webSocket = null;
if ('WebSocket' in window){
webSocket = new WebSocket("ws://localhost:8888/mos/websocket/"+sendUserId);
}else{
layer.msg('您的浏览器不支持websocket')
}
webSocket.onopen = function () {
layer.msg('连接成功')
}
webSocket.onerror = function (error) {
layer.msg('连接失败',error)
}
webSocket.onclose = function () {
layer.msg('连接关闭')
}
webSocket.onmessage = function (event) {
//处理文件类型
if (event.data instanceof Blob){
$("#imgMsg").attr("src",URL.createObjectURL(event.data));
$("#imgMsg").show();
} else {
$("#content").html(event.data)
}
};
});
</script>
</html>
websocket添加字节流的消息支持
@OnMessage
public void onMsg(ByteBuffer fileByteBuffer, Session session) throws IOException {
// 断点续传、大文件切片等等处理
log.info("msg from {} and msg type is ByteBuffer ", session.getId());
session.getBasicRemote().sendBinary(fileByteBuffer);
}
文件上传大小限制
spring:
servlet:
multipart:
max-file-size: 20MB
max-request-size: 40MB