微信聊天系统

socket.io

Node.js中使用socket的一个包。使用它可以很方便地建立服务器到客户端的sockets连接,发送事件与接收特定事件。

  • 通过npm进行安装 npm install socket.io 。
  • 安装后在node_modules文件夹下新生成了一个socket.io文件夹,其中我们可以找到一个socket.io.js文件。将它引入到HTML页面,这样我们就可以在前端使用socket.io与服务器进行通信了。
  • 同时服务器端的server.js里跟使用express一样,也要通过 require('socket.io') 将其引入到项目中,这样就可以在服务器端使用socket.io了。
    需要前后端都引入socket.io
  • 原理,服务器保存好所有的 Client->Server 的 Socket 连接,Client A 发送消息给 Client B 的实质是:Client A -> Server -> Client B。
    即 Client A 发送类似 {from:'Client A', to:'Client B', body: 'hello'} 的数据给 Server。Server 接收数据根据 to值找到 Client B 的 Socket 连接并将消息转发给 Client B

socket.io的使用

  • 使用socket.io,其前后端句法是一致的,即通过socket.emit()来激发一个事件,通过socket.on()来侦听和处理对应事件。这两个事件通过传递的参数进行通信。

自己聊天页面的实现

页面框架的实现


微信聊天系统_第1张图片
image.png

微信聊天系统_第2张图片
image.png
socket.io实现两个在线的人聊天

建立用户表的数据结构

var userSchema = new Schema({
  username: String,
  password: String,
  phone: String,
  friend:[]
});

建立friend表

var friendSchema = new Schema({
    friendID:String
});

建立message表

var msgSchema = new Schema({
  friendID:String,
  usrID:String,
  content:String,
  status:Number
});
添加用户登录,如果用户登录的话,把该用户加入到在线的user中去

在bin>www里面添加代码

var io = require('socket.io').listen(server);
var users=[];
io.on('connection', function(socket) {
  socket.on('login', function(usrName) {
    if (users.indexOf(usrName) > -1) {
      console.log("user existed");
    } else {
      socket.userIndex = users.length;
      socket.username = usrName;
      users.push(usrName);
      console.log(usrName);
      io.sockets.emit('system', usrName); //向所有连接到服务器的客户端发送当前登陆用户的昵称
    };
  });
  socket.on('chat message', function(msg){
    socket.broadcast.emit('newMsg', socket.username, msg);
  });

在前端public>js>chatList.js添加代码用来添加显示对话

    function init() {
        var socket = io();
        $('#loginBtn').click(function (){
            var username = $.cookie('username');
            socket.emit('login', username);
        });
        $('.inputMsg').submit(function () {
            var msg=$('#messageInput').val();
            $('#messageInput').val('');
            socket.emit('chat message',msg);
            displayNewMsg('me', msg);
            return false;
        });
        socket.on('newMsg', function(user, msg) {
            displayNewMsg(user, msg);
        });
    }
   //用来判断是自己的消息还是别人的消息
    function displayNewMsg(user, msg) {
        var itemArr = [];
        itemArr.push('
  • '); itemArr.push('
    '); itemArr.push('time'); itemArr.push('
    '); itemArr.push('
    '); itemArr.push(''); itemArr.push('

    '+msg+'

    '); itemArr.push('
    '); itemArr.push('
  • '); $('.historyMsg ul').append(itemArr.join('')); }
    微信聊天系统_第3张图片
    image.png

    你可能感兴趣的:(微信聊天系统)