亲宝软件园·资讯

展开

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

haeasringnar 人气:0

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模块实现点对点实时通讯,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

加载全部内容

相关教程
猜你喜欢
用户评论