socket.io + vue.js 简易聊天室

本文主要分享一个简易版的聊天室

项目地址

https://github.com/zuank/socket

测试地址 

http://yuehao.duapp.com/chat/

服务端配置

开启服务

const server = app.listen(port, () => {
  console.log(`technode is on port ${port} |`);
});

接入socket.io

const io = require('socket.io').listen(server);

socket配置

socket.emit 为广播

socket.broadcast.emit 为广播给其他用户

io.sockets.on('connection', (socket) => {
  socket.on('set nickname', (name) => {
    socket.nickname = name;
    socket.broadcast.emit('new user', {
      nickname: name,
      type: 'user',
    });
    socket.emit('login', {
      nickname: name,
      id: socket.id,
    });
  });
  socket.on('new dialog', (str) => {
    io.emit('new dialog', {
      value: str,
      nickname: socket.nickname,
      type: 'dialog',
    });
  });
});

前端配置

连接服务端

var socket = io.connect('/')

向服务端发送信息

socket.emit('set nickname', this.username)

接收来自服务端的信息

socket.on('new user', function(data) {
  console.log(data)
  app.messagelist.push(data)
})

你可能感兴趣的:(socket.io,vue.js,node.js)