0
点赞
收藏
分享

微信扫一扫

WebSocket 基本使用

Spinach菠菜 2022-02-04 阅读 85

服务端:

const ws = require("nodejs-websocket");
const server = ws.createServer(function (con) {
  console.log("websocket 服务端");
  con.on("text", function (str) {
    con.sendText(str);
  });
  // setTimeout(function () {
  //   con.sendText("来自服务端的消息");
  // }, 3000);
  con.on("error", function (err) {
    console.log(err);
  });
});
server.listen(2333);

客户端:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="text" id="text">
  <button id="btn" type="button">发送</button>

  <script type="text/javascript">
    const ws = new WebSocket('ws://localhost:2333')
    // ws.onopen = function (e) {
    //   ws.send('来自客户端的信息')
    // }
    // ws.onmessage = function (e) {
    //   console.log(e.data);
    // }
    ws.onopen = function () {
      document.getElementById('btn').onclick = function () {
        ws.send(document.getElementById('text').value);
      }
    }
    ws.onmessage = function (e) {
      // document.body.innerHTML += `<p>${e.data}</p>`
      let p = document.createElement('p')
      p.innerHTML = e.data;
      // appendChild() 方法可向节点的子节点列表的末尾添加新的子节点
      document.body.appendChild(p);
    }
  </script>
</body>

</html>
举报

相关推荐

0 条评论