-
-
Save jiangzm/4474f2c2f601b23d306235b2233fbe03 to your computer and use it in GitHub Desktop.
websocket sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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