一、WebSocket是HTML5出的东西(协议),也就是说HTTP协议没有变化,或者说没关系,但HTTP是不支持持久连接的(长连接,循环连接的不算)
二、WebSocket是一种双向通信协议,也叫服务器推送技术。在建立连接后,WebSocket服务器端和客户端都能主动向对方发送或接收数据,就像Socket一样
WebSocket需要像TCP一样,先建立连接,连接成功后才能相互通信。
以往大部分是客户端向服务器端发送数据,websocket可实现服务器端向客户端发送数据。
1.在uniapp中使用websocket:
uniapp 在androd上不支持原生的websocket,uni-app请使用uni.connectSocket
前端代码:
return里:
socketTask: null,
// 确保websocket是打开状态
is_open_socket: false,
onshow()里:
this.connectSocketInit(); // 一进入页面就会建立连接
methods里:
// 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit() {
// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
this.socketTask = uni.connectSocket({
url: "ws://后台的接口地址",
data: {
user: uni.getStorageSync('user_info').id,
},
// 接口调用成功的回调函数
success(data) {
// console.log("websocket正在连接");
},
fail(data) {
// console.log('websocket连接失败')
},
});
// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
//连接成功时回调
this.socketTask.onOpen((res) => {
// console.log("WebSocket连接正常打开中");
this.is_open_socket = true;
//收到信息的回调
this.socketTask.onMessage((res) => {
// console.log("收到服务器内容:" + res.data);
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
innerAudioContext.src = 'https://音频地址.mp3'
innerAudioContext.onPlay(() => {
// console.log('开始播放');
uni.showToast({
title: ' 任务大厅来新订单了,请尽快接单! ',
duration: 1000,
position: "top",
});
});
innerAudioContext.onError((res) => {
console.log(res.errMsg);
console.log(res.errCode);
});
});
})
// 这里仅是事件监听【如果socket关闭了会执行】
// this.socketTask.onClose(() => {
// console.log("websocket关闭")
// })
// },
// 关闭websocket【离开这个页面的时候执行关闭】
// closeSocket() {
// this.socketTask.close({
// success(res) {
// this.is_open_socket = false;
// console.log("关闭成功", res)
// },
// fail(err) {
// console.log("关闭失败", err)
// }
// })
// },
}
2.在vue中使用websocket:
前端代码:
<script>
export default {
data() {
return {
socket:null,
userId:localStorage.getItem("ms_uuid"),
toUserId:'2',
content:'3'
}
},
methods: {
openSocket() {
if (typeof WebSocket == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
//var socketUrl="${request.contextPath}/im/"+$("#userId").val();
var socketUrl =
"http://localhost:8081/imserver/" + this.userId;
socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
console.log(socketUrl);
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
this.socket = new WebSocket(socketUrl);
//打开事件
this.socket.onopen = function() {
console.log("websocket已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
this.socket.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
this.socket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
this.socket.onerror = function() {
console.log("websocket发生了错误");
};
}
},
sendMessage() {
if (typeof WebSocket == "undefined") {
console.log("您的浏览器不支持WebSocket");
} else {
console.log("您的浏览器支持WebSocket");
console.log(
'{"toUserId":"' +
this.toUserId +
'","contentText":"' +
this.content +
'"}'
);
this.socket.send(
'{"toUserId":"' +
this.toUserId +
'","contentText":"' +
this.content +
'"}'
);
}
}
网友评论