自己项目,封装的webSocket.js
import store from "../store";
import { socketUrl } from "./global_variable";
let socket;
// 是否已连接
let state = 0;
export function closeLink() {
socket.close();
}
// websocket发送消息
export function SendMsg(msg) {
if (state === 1) {
// 需要使用json字符串
socket.send(JSON.stringify(msg));
} else {
socket = new WebSocket(socketUrl);
socket.onopen = function() {
state = 1;
// alert('数据发送中...');
};
}
}
// 连接和接收的消息处理
export function oneConnect() {
socket = new WebSocket(socketUrl);
try {
socket.onopen = function(msg) {
state = 1;
// const msgContent = JSON.parse(msg.data);
};
// 自己发送的内容、和接收别人发送的消息。回调都是这一个方法
socket.onmessage = function(msg) {
const msgContent = JSON.parse(msg.data);
if (msgContent.MsgType > -1) {
const contentMsg = {
Id: msgContent.Id,
CustomerSysNo: msgContent.CustomerSysNo,
MsgType: msgContent.MsgType == 2 ? 5 : msgContent.MsgType,
Content: msgContent.Content,
CreatedDate: msgContent.Date,
NickName: msgContent.NickName,
HeadImage: msgContent.HeadImage,
IsRead: false,
isStudents: true,
MediaDuration: parseInt(msgContent.MediaDuration),
CoLectorName: msgContent.CoLectorName
};
if (
contentMsg.HeadImage == "" ||
contentMsg.HeadImage == null ||
contentMsg.HeadImage == undefined
) {
contentMsg.HeadImage =
"xxxxxxxxxxxxxxxxxx.png";
}
// 这边我因为是vue项目。这是使用的vuex
store.commit("addMsg", contentMsg);
}
};
// 连接不稳定时,在关闭的时候继续连接websocket
socket.onclose = function() {
state = 0;
oneConnect();
// 关闭 websocket
// socket.close()
};
} catch (ex) {
console.err(ex);
}
}
页面使用
<button @click="clickButton">{{ id + 1 }}</button>
clickButton () {
this.id++
var msg = {}
msg.Content = this.id // Content 服务器端定义
msg.CustomerSysNo = 0
SendMsg(msg)
}