欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

nodejs 使用nodejs-websocket模块实现点对点实时通讯

程序员文章站 2023-11-05 16:03:52
1、首先安装好nodejs-websocket npm install nodejs-websocket --save -g 2、编写服务端 var ws =...

1、首先安装好nodejs-websocket

npm install nodejs-websocket --save -g

2、编写服务端

var ws = require("nodejs-websocket")
var alluserdata = new array()
// scream server example: "hi" -> "hi!!!"
var server = ws.createserver(function (conn) {
  console.log("new connection")
  conn.on("text", function (str) {
    console.log("received "+str)
    alluserdata.push({
      'id':str,
      'ws':conn
    })
    conn.sendtext(str.touppercase()+"!!!")
  })
  conn.on("close", function (code, reason) {
    console.log("connection closed")
    // 当用户退出的时候捕捉到退出的用户
    for (var i=0 in alluserdata) {
      if (alluserdata[i].ws == conn) {
        console.log(alluserdata[i])
      }
    }
  })
}).listen(8001)

3、简易客户端

<!doctype html>
<html>
<head>
  <title>django-websocket</title>
  <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script type="text/javascript">//<![cdata[
  $(function () {
    $('#connect_websocket').click(function () {
      if (window.s) {
        window.s.close()
      }
      /*创建socket连接*/
      var socket = new websocket("ws://127.0.0.1:8001");
      socket.onopen = function () {
        console.log('websocket open');//成功连接上websocket
      };
      socket.onmessage = function (e) {
        console.log('message: ' + e.data);//打印出服务端返回过来的数据
        $('#messagecontainer').prepend('<p>' + e.data + '</p>');
      };
      // call onopen directly if socket is already open
      if (socket.readystate == websocket.open) socket.onopen();
      window.s = socket;
    });
    $('#send_message').click(function () {
      //如果未连接到websocket
      if (!window.s) {
        alert("websocket未连接.");
      } else {
        window.s.send($('#message').val());//通过websocket发送数据
      }
    });
    $('#close_websocket').click(function () {
      if (window.s) {
        window.s.close();//关闭websocket
        console.log('websocket已关闭');
      }
    });
  });
  //]]></script>
</head>
<body>
<br>
<input type="text" id="message" value="user1"/>
<button type="button" id="connect_websocket">连接 websocket</button>
<button type="button" id="send_message">发送 message</button>
<button type="button" id="close_websocket">关闭 websocket</button>
<h1>received messages</h1>
<div id="messagecontainer">
</div>
</body>
</html>

总结

以上所述是小编给大家介绍的nodejs 使用nodejs-websocket模块实现点对点实时通讯,希望对大家有所帮助