• express+mongodb+socket.io


    node后端代码

    // Setup basic express server
    var express = require('express');
    var app = express();
    var path = require('path');
    var server = require('http').createServer(app);
    var io = require('socket.io')(server);
    var port = process.env.PORT || 9000;
    var MongoClient = require('mongodb').MongoClient;
    var DB_CONN_STR = 'mongodb://172.16.81.36:27017/runoob';
    
    
    server.listen(port, function () {
      console.log('Server listening at port %d', port);
    });
    
    // Routing
    app.use(express.static(path.join(__dirname, 'public')));
    
    // Chatroom
    
    var numUsers = 0;
    
    app.get('/setUsername', function (req, res) {
    
        if(req.query.username!=undefined&&req.query.username!=''&&req.query.password!=undefined&&req.query.password!=''){
    
            var selectData = function(db, callback) {
              //连接到表
              var collection = db.collection('site');
              //查询数据
              var whereStr = {"username":req.query.username,"password":req.query.password};
              collection.find(whereStr).toArray(function(err, result) {
                if(err)
                {
                  console.log('Error:'+ err);
                  return;
                }
                callback(result);
              });
            }
    
    
            var insertData = function(db, callback) {
                //连接到表 site
                var collection = db.collection('site');
                //插入数据
                var data = [{"username":req.query.username,"password":req.query.password}];
                collection.insert(data, function(err, result) {
                    if(err)
                    {
                        console.log('Error:'+ err);
                        return;
                    }
                    callback(result);
                });
            }
    
            MongoClient.connect(DB_CONN_STR, function(err, db) {
                console.log("连接成功!");
                selectData(db, function(result) {
                //    console.log(result.length);
                   if(result==''){
                       console.log("请输入真实姓名");
                       res.send({
                             errorCode:-1,
                             errorMsg:'请输入正确的姓名和密码'
                        });
                       /*
                       注册
                       */
                    //    insertData(db, function(result) {
                        //    console.log(result);
                        //    res.send({
                        //        errorCode:-1,
                        //        errorMsg:'请输入真实姓名'
                        //    });
                    //        db.close();
                    //    });
                   }else{
                       console.log("登录成功");
                       res.send({
                           errorCode:0,
                           errorMsg:'登录成功'
                       });
                   }
                   db.close();
                 });
            });
    
        }else{
            res.send({
                errorCode:-1,
                errorMsg:'姓名和密码不能为空'
            });
        }
    })
    
    
    io.on('connection', function (socket) {
    
      var addedUser = false;
    
      // when the client emits 'new message', this listens and executes
      socket.on('new message', function (data) {
        // we tell the client to execute 'new message'
        socket.broadcast.emit('new message', {
          username: socket.username,
          message: data
        });
      });
    
      // when the client emits 'add user', this listens and executes
      socket.on('add user', function (username) {
        if (addedUser) return;
    
        // we store the username in the socket session for this client
        socket.username = username;
        ++numUsers;
        addedUser = true;
        socket.emit('login', {
          numUsers: numUsers
        });
        // echo globally (all clients) that a person has connected
        socket.broadcast.emit('user joined', {
          username: socket.username,
          numUsers: numUsers
        });
      });
    
      // when the client emits 'typing', we broadcast it to others
      socket.on('typing', function () {
        socket.broadcast.emit('typing', {
          username: socket.username
        });
      });
    
      // when the client emits 'stop typing', we broadcast it to others
      socket.on('stop typing', function () {
        socket.broadcast.emit('stop typing', {
          username: socket.username
        });
      });
    
      // when the user disconnects.. perform this
      socket.on('disconnect', function () {
        if (addedUser) {
          --numUsers;
    
          // echo globally that this client has left
          socket.broadcast.emit('user left', {
            username: socket.username,
            numUsers: numUsers
          });
        }
      });
    });

    前端代码

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>即时通讯</title>
      <link rel="stylesheet" href="style.css">
    </head>
    <body>
      <ul class="pages">
    
        <li class="chat page">
          <div class="chatArea">
            <ul class="messages">
                <!-- 信息 -->
            </ul>
          </div>
          <!-- 输入框 -->
          <input class="inputMessage" placeholder="Type here..."/>
        </li>
    
        <!-- 登录页面 -->
        <li class="login page">
          <div class="form">
            <h3 class="title">请设置你的名字</h3>
            <input class="usernameInput" type="text" maxlength="14" />
            <h3 class="title">请设置你的密码</h3>
            <input class="passwordInput" type="password" maxlength="14" />
            <br>
            <br>
            <br>
            <input type="button" name="" value="登录" class="loginBtn" style='height:60px;160px;font-size:30px;'>
          </div>
        </li>
    
      </ul>
      <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
      <script src="/socket.io.js"></script>
      <script src="/main.js"></script>
    </body>
    </html>
    

      main.js文件

    $(function() {
      var FADE_TIME = 150; // ms
      var TYPING_TIMER_LENGTH = 400; // ms
      var COLORS = [
        '#e21400', '#91580f', '#f8a700', '#f78b00',
        '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
        '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
      ];
    
      // Initialize variables
      var $window = $(window);
      var $usernameInput = $('.usernameInput'); // Input for username
      var $messages = $('.messages'); // Messages area
      var $inputMessage = $('.inputMessage'); // Input message input box
    
      var $loginPage = $('.login.page'); // The login page
      var $chatPage = $('.chat.page'); // The chatroom page
    
      // Prompt for setting a username
      var username;
      var connected = false;
      var typing = false;
      var lastTypingTime;
      // var $currentInput = $usernameInput.focus();
      $('.loginBtn').click(function(){
          setUsername ();
      })
      var socket = io();
    
      function addParticipantsMessage (data) {
        var message = '';
        if (data.numUsers === 1) {
          message += "有 1 个人加入了聊天室";
        } else {
          message += "有 " + data.numUsers + " 个人加入了聊天室";
        }
        log(message);
      }
    
    
    
      // Sets the client's username
      function setUsername () {
        username = cleanInput($usernameInput.val().trim());
        var password=$('.passwordInput').val();
        var url='http://172.16.81.36:9000/setUsername';
        console.log(username);
        $.ajax({
            url:url,
            type:'get',
            data:{
                username:username,
                password:password
            },
            success:function(res){
                console.log(res);
                if (res.errorCode==0) {
                    $loginPage.fadeOut();
                    $chatPage.show();
                    $loginPage.off('click');
                    // $currentInput = $inputMessage.focus();
    
                    // Tell the server your username
                    socket.emit('add user', username);
                }else{
                    alert(res.errorMsg)
                    username=false;
                }
            }
        })
        // If the username is valid
    
      }
    
      // Sends a chat message
      function sendMessage () {
        var message = $inputMessage.val();
        // Prevent markup from being injected into the message
        message = cleanInput(message);
        // if there is a non-empty message and a socket connection
        if (message && connected) {
          $inputMessage.val('');
          addChatMessage({
            username: username,
            message: message
          });
          // tell server to execute 'new message' and send along one parameter
          socket.emit('new message', message);
        }
      }
    
      // Log a message
      function log (message, options) {
        var $el = $('<li>').addClass('log').text(message);
        addMessageElement($el, options);
      }
    
      // Adds the visual chat message to the message list
      function addChatMessage (data, options) {
        // Don't fade the message in if there is an 'X was typing'
        var $typingMessages = getTypingMessages(data);
        options = options || {};
        if ($typingMessages.length !== 0) {
          options.fade = false;
          $typingMessages.remove();
        }
    
        var $usernameDiv = $('<span class="username"/>')
          .text(data.username)
          .css('color', getUsernameColor(data.username));
        var $messageBodyDiv = $('<span class="messageBody">')
          .text(data.message);
    
        var typingClass = data.typing ? 'typing' : '';
        var $messageDiv = $('<li class="message"/>')
          .data('username', data.username)
          .addClass(typingClass)
          .append($usernameDiv, $messageBodyDiv);
    
        addMessageElement($messageDiv, options);
      }
    
      // Adds the visual chat typing message
      function addChatTyping (data) {
        data.typing = true;
        data.message = '用户正在输入';
        addChatMessage(data);
      }
    
      // Removes the visual chat typing message
      function removeChatTyping (data) {
        getTypingMessages(data).fadeOut(function () {
          $(this).remove();
        });
      }
    
      // Adds a message element to the messages and scrolls to the bottom
      // el - The element to add as a message
      // options.fade - If the element should fade-in (default = true)
      // options.prepend - If the element should prepend
      //   all other messages (default = false)
      function addMessageElement (el, options) {
        var $el = $(el);
    
        // Setup default options
        if (!options) {
          options = {};
        }
        if (typeof options.fade === 'undefined') {
          options.fade = true;
        }
        if (typeof options.prepend === 'undefined') {
          options.prepend = false;
        }
    
        // Apply options
        if (options.fade) {
          $el.hide().fadeIn(FADE_TIME);
        }
        if (options.prepend) {
          $messages.prepend($el);
        } else {
          $messages.append($el);
        }
        $messages[0].scrollTop = $messages[0].scrollHeight;
      }
    
      // Prevents input from having injected markup
      function cleanInput (input) {
        return $('<div/>').text(input).html();
      }
    
      // Updates the typing event
      function updateTyping () {
        if (connected) {
          if (!typing) {
            typing = true;
            socket.emit('typing');
          }
          lastTypingTime = (new Date()).getTime();
    
          setTimeout(function () {
            var typingTimer = (new Date()).getTime();
            var timeDiff = typingTimer - lastTypingTime;
            if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
              socket.emit('stop typing');
              typing = false;
            }
          }, TYPING_TIMER_LENGTH);
        }
      }
    
      // Gets the 'X is typing' messages of a user
      function getTypingMessages (data) {
        return $('.typing.message').filter(function (i) {
          return $(this).data('username') === data.username;
        });
      }
    
      // Gets the color of a username through our hash function
      function getUsernameColor (username) {
        // Compute hash code
        var hash = 7;
        for (var i = 0; i < username.length; i++) {
           hash = username.charCodeAt(i) + (hash << 5) - hash;
        }
        // Calculate color
        var index = Math.abs(hash % COLORS.length);
        return COLORS[index];
      }
    
      // Keyboard events
    
      $window.keydown(function (event) {
        // Auto-focus the current input when a key is typed
        if (!(event.ctrlKey || event.metaKey || event.altKey)) {
        //   $currentInput.focus();
        }
        // When the client hits ENTER on their keyboard
        if (event.which === 13) {
            // console.log(username);
          if (username) {
            sendMessage();
            socket.emit('stop typing');
            typing = false;
          } else {
    
            setUsername();
          }
        }
      });
    
      $inputMessage.on('input', function() {
        updateTyping();
      });
    
      // Click events
    
      // Focus input when clicking anywhere on login page
      $loginPage.click(function () {
        // $currentInput.focus();
      });
    
      // Focus input when clicking on the message input's border
      $inputMessage.click(function () {
        $inputMessage.focus();
      });
    
      // Socket events
    
      // Whenever the server emits 'login', log the login message
      socket.on('login', function (data) {
        connected = true;
        // Display the welcome message
        var message = "欢迎你来到前端侃大山~";
        log(message, {
          prepend: true
        });
        addParticipantsMessage(data);
      });
    
      // Whenever the server emits 'new message', update the chat body
    
      socket.on('new message', function (data) {
        addChatMessage(data);
      });
    
      // Whenever the server emits 'user joined', log it in the chat body
      socket.on('user joined', function (data) {
        log(data.username + ' 加入了聊天室');
        addParticipantsMessage(data);
      });
    
      // Whenever the server emits 'user left', log it in the chat body
      socket.on('user left', function (data) {
        log(data.username + ' 离开了聊天室');
        addParticipantsMessage(data);
        removeChatTyping(data);
      });
    
      // Whenever the server emits 'typing', show the typing message
      socket.on('typing', function (data) {
        addChatTyping(data);
      });
    
      // Whenever the server emits 'stop typing', kill the typing message
      socket.on('stop typing', function (data) {
        removeChatTyping(data);
      });
    
      socket.on('disconnect', function () {
        log('小主,掉线了~');
      });
    
      socket.on('reconnect', function () {
        log('you have been reconnected');
        if (username) {
          socket.emit('add user', username);
        }
      });
    
      socket.on('reconnect_error', function () {
        log('链接服务器失败~');
      });
    
    });
    

      

  • 相关阅读:
    PHP中使用CURL实现GET和POST请求
    PHP 正则表达式匹配函数 preg_match 与 preg_match_all
    微信跳转黑科技:微信跳转技术让微信电商从此不缺流量
    PHP通过get方法获得form表单数据方法总结
    php获取微信基础接口凭证Access_token
    PHP命名空间与自动加载类详解
    PHP如何搭建百度Ueditor富文本编辑器
    PHP调用微博接口实现微博登录的方法示例
    PHP常用日期加减计算方法实例
    微信公众平台---带参数二维码生成和扫描事件
  • 原文地址:https://www.cnblogs.com/yiyi17/p/7561298.html
Copyright © 2020-2023  润新知