How to make an native nodejs websocket server with the http module?

编程入门 行业动态 更新时间:2024-10-06 12:28:03

How to make an native nodejs <a href=https://www.elefans.com/category/jswz/34/1771432.html style=websocket server with the http module?"/>

How to make an native nodejs websocket server with the http module?

我已经尝试通过从其他来源放置一些代码来自己制作一个,但它不起作用。这是我所拥有的:

server.on("upgrade",(req,socket)=>{
    let accept = crypto.Hash("sha1").update(req.headers["sec-websocket-key"]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64")
    const headers = [
    'HTTP/1.1 101 Switching Protocols',
    'Upgrade: WebSocket',
    'Connection: Upgrade',
    'Sec-WebSocket-Accept: '+accept,
        ''
  ].map(line => line.concat('\r\n')).join('')
    socket.write(headers)
    socket.on("data", (data)=>{
        console.log('server!', data.toString("utf8")) // showing up as �������9
        socket.write("hellow!!") // this is supposed to write back a message, but the client recieves "Invalid Frame Header"
    })
    socket.on("error",(err)=>{
        console.log(err)
    })
    socket.on("end",()=>{
        console.log("disconnect")
    })
})

server.listen(80, () => {
  console.log("Started.")
})

我想解码从客户端收到的数据并发回消息。我在网上找不到很好的例子。

回答如下:

更多推荐

How to make an native nodejs websocket server with the http module?

本文发布于:2024-05-13 16:01:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759985.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:websocket   nodejs   native   module   http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!