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
      });
    }
  });
});
复制代码

前端代码

  main.js文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
$(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('链接服务器失败~');
  });
 
});

  

 

posted @   地铁程序员  阅读(284)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示