Skip to content

Instantly share code, notes, and snippets.

@jiangzm
Last active August 27, 2020 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiangzm/4474f2c2f601b23d306235b2233fbe03 to your computer and use it in GitHub Desktop.
Save jiangzm/4474f2c2f601b23d306235b2233fbe03 to your computer and use it in GitHub Desktop.
websocket sample code
const ws = new WebSocket("ws://localhost:8000");
let certPromise = null;
const sendFile = () => new Promise((resolve) => {
const reader = new FileReader();
const file = document.getElementById('filename').files[0];
reader.onload = (event) => {
//发送文件
ws.send(event.target.result);
resolve(true);
}
reader.readAsArrayBuffer(file);
});
const requestCert = () => new Promise((resolve) => {
// 请求证书
const data = {}; //
fetch("http://localhost/api/cert", {
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json'
},
method: 'POST'
}).then(res => {
resolve(res.text());
})
});
ws.onopen = () => {
console.log("连接已打开");
// 异步发送文件
sendFile();
// 申请证书
certPromise = requestCert();
};
ws.onmessage = async (event) => {
const message = JSON.parse(event.data);
if (message.type === "FILE_RECEIVED") {
const cert = await certPromise;
ws.send(cert);
} else if (message.type === "XXXX") {
// to do
}
};
ws.onclose = () => {
console.log("连接已关闭");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment