万字长文,一篇吃透WebSocket:概念、原理、易错常识、动手实践(27)
2023-04-29 来源:飞速影视
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8"});
res.end("大家好,我是阿宝哥。感谢你阅读“你不知道的WebSocket”");
});
server.on("upgrade", function(req, socket) {
socket.on("data", (buffer) => {
const message = parseMessage(buffer);
if(message) {
console.log("Message from client:" message);
socket.write(constructReply({ message }));
} else if(message === null) {
console.log("WebSocket connection closed by the client.");
}
});
if(req.headers["upgrade"] !== "websocket") {
socket.end("HTTP/1.1 400 Bad Request");
return;
}
// 读取客户端提供的Sec-WebSocket-Key
const secWsKey = req.headers["sec-websocket-key"];
// 使用SHA-1算法生成Sec-WebSocket-Accept
const hash = generateAcceptValue(secWsKey);
// 设置HTTP响应头
const responseHeaders = [
"HTTP/1.1 101 Web Socket Protocol Handshake",
"Upgrade: WebSocket",
"Connection: Upgrade",
本站仅为学习交流之用,所有视频和图片均来自互联网收集而来,版权归原创者所有,本网站只提供web页面服务,并不提供资源存储,也不参与录制、上传
若本站收录的节目无意侵犯了贵司版权,请发邮件(我们会在3个工作日内删除侵权内容,谢谢。)
www.fs94.org-飞速影视 粤ICP备74369512号