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)
})
    原文作者:zuank
    原文地址: https://segmentfault.com/a/1190000010350918
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞