nodejs-websocket初使用

主要实现一个客户端给服务端发送消息,服务端再推送给客户端,其中客户端是有多个

首先来看一下效果

 具体代码实现:

服务端:

首先需要安装依赖

npm i nodejs-websocket -S
  
  

然后新建一个app.js文件

app.js代码如下: 


   
   
  1. const ws = require( 'nodejs-websocket'); //引入websocket
  2. const prot = 8088;
  3. const server = ws.createServer( connection => {
  4. // console.log('有一名用户连接进来了...')
  5. connection.on( "text", function (str) {
  6. // console.log('我来接收客户端发过来的消息' + str)
  7. // connection.sendText(str);//返回给客户端的数据
  8. server.connections.forEach( function (conn) {
  9. conn.sendText(str) //返回给所有客户端的数据(相当于公告、通知)
  10. })
  11. })
  12. //监听关闭
  13. connection.on( "close", function (code, reason) {
  14. console.log( "Connection closed")
  15. })
  16. //监听异常
  17. connection.on( "error",() => {
  18. console.log( '服务异常关闭...')
  19. })
  20. }).listen(prot)

客户端:

此处略过客户端的css部分,因为并不好看


   
   
  1. <!-- html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <link rel="stylesheet" type="text/css" href="./css/cssReset.css"/>
  8. <link rel="stylesheet" type="text/css" href="./css/index.css"/>
  9. <title> </title>
  10. </head>
  11. <body>
  12. <div id="box">
  13. <div class="msg" id="msg"> </div>
  14. <div class="bottom">
  15. <input type="text" id="inp" value="" />
  16. <button type="button" id="btn">提交 </button>
  17. </div>
  18. </div>
  19. <script type="text/javascript" src="./js/index.js"> </script>
  20. </body>
  21. </html>

   
   
  1. //javascript
  2. let ws = new WebSocket( 'ws://localhost:8088'); //实例化websocket
  3. let val = '';
  4. let btn = document.getElementById( 'btn'); //发消息按钮
  5. let msg = document.getElementById( 'msg'); //存消息容器
  6. //发消息
  7. ws.onopen = function(){
  8. //点击按钮发送消息
  9. btn.onclick = function(){
  10. val = document.getElementById( 'inp').value;
  11. ws.send(val); //发送给服务端数据
  12. }
  13. };
  14. //收消息
  15. ws.onmessage = function (e) {
  16. //e 接收服务端返回的数据
  17. var received_msg = e.data;
  18. msg.innerHTML += received_msg += '<br>'
  19. };
  20. //关闭连接
  21. ws.onclose = function(){
  22. console.log( "连接已关闭...");
  23. };
  24. //抛错
  25. ws.onerror = function () {
  26. console.log( '服务异常关闭...')
  27. }

此处粘贴一个 nodejs-websocket 在npm上的文档  点击查看

猜你喜欢

转载自www.cnblogs.com/xue-shuai/p/12446559.html