gogogo
管理员
管理员
  • UID25
  • 粉丝0
  • 关注0
  • 发帖数1377
阅读:1918回复:0

nodejs-websocket 的简单用法和安装

楼主#
更多 发布于:2022-06-15 16:14
网上很多的websocket我都看不懂,看了个视频才慢慢懂了点
视频链接:https://www.imooc.com/learn/861
以下都是根据老师的步伐走的
先打开cmd 或者 powershell 键入 cd 进入服务端的地址,再键入 npm install nodejs-websocket
还有nodejs也要安装 地址:https://nodejs.org/en/
安装成功后,在nodejs-websocket下新建js
js 服务端大致代码:
var ws = require('nodejs-websocket');
var port=3000
var server = ws.createServer(function(conn){
    //受到连接触发//
   //在服务端cmd安装npm install nodejs-websocket//
    console.log('new connection');
    conn.on("text",function(str){
        // 收到信息触发     接收 //
        console.log("received"+str)
        boardcast(str) // 广播消息 //
        conn.sendText(str) // 发送 数据 //
    })
    conn.on("close",function(code,reason){
        // 断开连接触发 //
        console.log("connection closed")
    })
    conn.on("error",function(err){
        // 出错触发 //
        console.log("header err")
        console.log(err)
    })
    function boardcast(str){  // 广播 //
    // server.connections  保存每个连接进来的用户 //
    server.connections.forEach(function(conn){   //  .forEach 是调用数组里每个元素  //
    conn.sendText(str)
    })
    }
}).listen(port)
console.log("websocket server listen port is" + port)




客户端的大致代码:



<html>
   <head>
   <title>first socket</title>
   </head>
   <body>
     <h1>myfitst room</h1>
    <input type="text" id="snedTxt" />
    <button id="sendb">发送</button>
    <div id="recv"></div>
      <script type="text/javascript">
      var ws = new WebSocket("ws://localhost:3000/");// 设置服务器地址 //
      ws.onopen=function(){  // onopen 连接触发 //
        console.log("websocket open");
        document.getElementById("recv").innerHTML="Connected";
                                   //  innerHTML 可以 获取 也可以 插入  //
                      
      }
      ws.onclose=function(){ // onclose 断开触发 //
        console.log("websocket close");
      }
      ws.onmessage =function(e){ // onmessage 接收到信息触发  //
      console.log(e.data);
      document.getElementById("recv").innerHTML = e.data;
 
      }
      document.getElementById("sendb").onclick=function(){ // 监测 id=“sendb”的 按钮 触发 onclick 就会发送数据 send //
        var txt = document.getElementById("snedTxt").value;
        ws.send(txt);
      }
      </script>
   </body>
</html>








html 直接运行
js 则要cmd cd到根目录 键入 node 文件名.js



这样就算成功了
游客


返回顶部