lsp-ws
v1.0.5
Published
webmsg项目的js客户端
Downloads
1
Readme
LWS
webmsg 项目的 js 客户端
用法
以 vue 项目作为演示,其他类似,不需要关注getQueryString
、ajax
、formatParams
这些方法,重点关注其他的
import LWS from "lsp-ws";
export default {
name: "LWS",
data() {
return {
topMessage: "",
normalMessage: "",
logContent: "",
roomId: "",
userId: "",
broadcastMessage: "",
target: "",
targetType: "room",
targetContent: "",
conn: null,
};
},
mounted() {
this.loaded();
},
methods: {
getQueryString(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
},
//创建ajax函数
ajax(options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
let params = this.formatParams(options.data, options.dataType);
//创建-第一步
let xhr;
xhr = new XMLHttpRequest();
//接收-第三步
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let status = xhr.status;
if (status >= 200 && status < 300) {
options.success &&
options.success(xhr.responseText, xhr.responseXML);
} else {
options.error && options.error(status);
}
}
};
//连接和发送-第二步
if (options.type === "GET") {
xhr.open("GET", options.url + "?" + params, true);
xhr.send(null);
} else if (options.type === "POST") {
xhr.open("POST", options.url, true);
//设置表单提交时的内容类型
if (options.dataType === "json") {
xhr.setRequestHeader("Content-Type", "application/json");
} else {
xhr.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
}
xhr.send(params);
}
},
formatParams(data, dataType) {
if (dataType === "json") {
return JSON.stringify(data);
} else {
let arr = [];
for (let name in data) {
arr.push(
encodeURIComponent(name) + "=" + encodeURIComponent(data[name])
);
}
arr.push(("v=" + Math.random()).replace(".", ""));
return arr.join("&");
}
},
normalSend() {
// 发送普通消息,目前只能发送ping字符串
// this.conn.ws对象为原生js Websocket对象
this.conn.ws.send(this.normalMessage);
},
disconnect() {
// 断开连接
this.conn.close();
},
joinRoom() {
// 加入房间
this.conn.join(this.roomId);
},
leaveRoom() {
// 离开房间
this.conn.leave(this.roomId);
},
register() {
// 自注册身份标识
this.conn.register(this.userId);
},
sendToTarget() {
// 点对点发送消息
this.conn.send(this.target, this.targetType, this.targetContent);
},
broadcast() {
// 发送广播
this.conn.broadcast(this.broadcastMessage);
},
apiSend() {
// api推送示例,后端使用,前端基本不用
this.ajax({
url: "http://127.0.0.1:8080/push",
type: "POST",
dataType: "json",
data: {
to: this.target,
type: this.targetType,
content: this.targetContent,
},
success: (response, xml) => {
this.topMessage = JSON.stringify(response) + JSON.stringify(xml);
},
error: (status) => {
this.topMessage = JSON.stringify(status);
},
});
},
loaded() {
let schema = "ws";
if (this.getQueryString("wss")) {
schema = "wss";
}
try {
// 创建LWS对象示实例
this.conn = LWS({
url: schema + "://127.0.0.1:8080",
// 设置open事件处理器
open: (ev) => {
console.log("[open]", ev);
},
// 设置close事件处理器
close: (ev) => {
console.log("[close]", ev);
this.logContent +=
"<div><i class='text-warning'>Connection closed.</i></div>";
},
// 设置error事件处理器
error: (ev) => {
console.log("[error]", ev);
},
// 设置message事件处理器
message: (ev, data) => {
console.log("[message]", data);
this.logContent += "<div>" + data + "</div>";
},
});
} catch (e) {
console.error(e);
}
},
},
};
部分常量
export const ToSystem = "system"; // 系统消息
export const ToGlobal = "global"; // 广播消息
export const TypeJoin = "join"; // 加入房间
export const TypeLeave = "leave"; // 离开房间
export const TypeRegister = "register"; // 注册客户端身份
export const TypeRoom = "room"; // 房间类消息
export const TypePersonal = "personal"; // 个人类消息
export const TypeGroup = "group"; // 用户组类消息
用于浏览器中
先引入index.browser.js
<script src="index.browser.js"></script>
设置配置选项,连接 websocket 服务器。
function connect(uid) {
if (conn) {
return;
}
if (window["WebSocket"]) {
let schema = "ws";
if (getQueryString("wss")) {
schema = "wss";
}
// 配置连接选项
const conOptions = {
url: schema + "://" + document.location.host + "?uid=" + uid,
close: function (evt) {
var item = document.createElement("div");
item.innerHTML = "<i class='text-warning'>Connection closed.</i>";
appendLog(item);
},
message: function (evt, data) {
console.log("got message: ", data, "original: ", evt.data);
const item = document.createElement("div");
item.innerText = data;
appendLog(item);
},
};
// 获得连接操作对象
conn = LWS(conOptions);
} else {
var item = document.createElement("div");
item.innerHTML = "<b>Your browser does not support WebSockets.</b>";
appendLog(item);
}
}
// ...业务逻辑处理
conn.join(roomId); // 加入房间
conn.leave(roomId); // 离开房间
conn.register(userId); // 注册用户
conn.broadcast(message); // 广播消息
conn.close(); // 关闭连接
浏览器版常量的用法
浏览器版常量可以通过LWS
来访问,如conn.send(LWS.ToSystem, LWS.TypeJoin, 'room2')
表示加入房间room2
。
LWS.ToSystem = ToSystem; // 系统消息
LWS.ToGlobal = ToGlobal; // 广播消息
LWS.TypeJoin = TypeJoin; // 加入房间
LWS.TypeLeave = TypeLeave; // 离开房间
LWS.TypeRegister = TypeRegister; // 注册客户端身份
LWS.TypeRoom = TypeRoom; // 房间类消息
LWS.TypePersonal = TypePersonal; // 个人类消息
LWS.TypeGroup = TypeGroup; // 用户组类消息