socket.io实现即时通讯

144 阅读1分钟

使用框架:Node.js 即时通讯:socket.io


package.json

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "^4.17.1",
    "socket.io": "^4.5.2"
  },
  "scripts": {
    "start": "node index.js"
  }
}

前台页面

<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

    <!-- 引入socket模块 -->
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js" rel="external nofollow" ></script>
    <script>
        $(function () {
          var socket = io();
          $('form').submit(function(){
            // 用户输入消息时,服务器接收 chat message 事件
            socket.emit('chat message', $('#m').val());
            $('#m').val('');
            return false;
          });
        // 捕获 chat message 事件,并将消息添加到页面中。现在客户端代码应该如下:
          socket.on('chat message', function(msg){
            // 此处传输的信息为后端传输而来的
            // 将信息渲染到页面
            $('#messages').append($('<li>').text(msg));
          });
        });
      </script>
    

  </body>
</html>

后端页面

var app = require('express')();
// Express 初始化 app 作为 HTTP 服务器的回调函数
var http = require('http').Server(app);

// 添加io模块 我们通过传入 http (HTTP 服务器) 对象初始化了 socket.io 的一个实例。
var io = require('socket.io')(http);

// 定义了一个路由 / 来处理首页访问。
app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
  });

// 监听 connection 事件来接收 sockets, 并将连接信息打印到控制台。
io.on('connection', function(socket){
    //  监听输入事件 通过前台传送的chat message事件捕获到对应信息
    socket.on('chat message', function(msg){
        console.log(msg)


        // 将消息发送给所有用户(此处可以更改未对应用户)包括发送者。 msg为用户输入的信息
        io.emit('chat message', msg);

        // 要将消息发给除特定 socket 外的其他用户,可以用 broadcast 标志:
        // socket.broadcast.emit('hi');
    });
  })

// 使 http 服务器监听端口 31100。
http.listen(3100, function(){console.log('listening on *:3100');});

使用步骤详解 请添加图片描述