当前位置: 首页 > article >正文

Vue.js 中集成 Socket.IO 实现实时聊天功能

前言

随着 Web 技术的发展,实时通信成为现代 Web 应用的重要组成部分。Socket.IO 是一个流行的库,支持及时、双向与基于事件的通信,适用于各种平台和设备。本文将介绍如何在 Vue.js 项目中集成 Socket.IO,实现一个简单的实时聊天应用。通过本文,读者将学习到如何设置服务器端和客户端的 Socket.IO 连接,以及如何处理消息的发送和接收

1.1 socket.io

https://socket.io/zh-CN/

支持及时、双向与基于事件的交流。它可以在每个平台、每个浏览器和每个设备上工作,可靠性和速度同样稳定。

在这里插入图片描述

1.1.1 创建项目 chat-example

$ npm init -y
$ cnpm i express@4 -S
$ cnpm i socket.io -S
// index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.get('/', (req, res) => {
  res.send('<h1>Hello world</h1>');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
$ node index.js

在这里插入图片描述

在这里插入图片描述

<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>
// index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.get('/', (req, res) => {
  // res.send('<h1>Hello world</h1>');
  res.sendFile(__dirname + '/index.html');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

在这里插入图片描述

// index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
// 构建socket服务
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  // res.send('<h1>Hello world</h1>');
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
  </body>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
  </script>
</html>
// index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
// 构建socket服务
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  // res.send('<h1>Hello world</h1>');
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

在这里插入图片描述

<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
  </body>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();


    var form = document.getElementById('form');
    var input = document.getElementById('input');
    // 点击发送,向服务器发送了一个名为 chat message的事件
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
      }
    });
  </script>
</html>
// index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
// 构建socket服务
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  // res.send('<h1>Hello world</h1>');
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

在这里插入图片描述

// index.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
// 构建socket服务
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  // res.send('<h1>Hello world</h1>');
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
    io.emit('chat message', msg); // 给前端广播接收到的消息
  });

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});
<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
  </body>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();


    var form = document.getElementById('form');
    var input = document.getElementById('input');
    // 点击发送,向服务器发送了一个名为 chat message的事件
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
      }
    });

    socket.on('chat message', function(msg) {
      var item = document.createElement('li');
      item.textContent = msg;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });
  </script>
</html>

如果想要加入昵称 - 传对象

<!-- index.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="nickname" placeholder="昵称" />
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
  </body>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();


    var form = document.getElementById('form');
    var input = document.getElementById('input');
    var nickname = document.getElementById('nickname');
    // 点击发送,向服务器发送了一个名为 chat message的事件
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      if (input.value) {
        socket.emit('chat message', {
          name: nickname.value,
          value: input.value
        });
        input.value = '';
      }
    });

    socket.on('chat message', function(msg) {
      var item = document.createElement('li');
      item.textContent = msg.name + ':' + msg.value;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });
  </script>
</html>

1.2 使用第三方美洽实现客服

参照美洽官方文档

https://meiqia.com/help/article/javascript/?_gl=1%2Au81i4j%2A_ga%2AODYyNDI0ODkzLjE2ODk3MzU0OTg.%2A_ga_5LJSE1G1G3%2AMTY4OTczNTQ5OC4xLjEuMTY4OTczNjE0Ny4wLjAuMA…#e9809ae8bf87e9858de7bdaee68c87e5ae9ae58886e9858de5aea2e69c8de68896e5aea2e69c8de7bb84

总结

通过本文的介绍,我们成功地在 Vue.js 项目中集成了 Socket.IO,实现了基本的实时聊天功能。我们从创建项目开始,逐步配置了 Express 和 Socket.IO 服务器,并在客户端通过 HTML 和 JavaScript 实现了消息的发送和接收。此外,我们还加入了昵称功能,使聊天更加个性化。


http://www.kler.cn/a/420912.html

相关文章:

  • 使用PaddlePaddle实现线性回归模型
  • 【Linux】常用命令二
  • 各大浏览器(如Chrome、Firefox、Edge、Safari)的对比
  • 【Gitlab】gitrunner并发配置
  • 设计模式 更新ing
  • 图像与文字的创意融合:使用Python进行视觉艺术创作
  • Microi 吾码:后端开发的创新引擎与代码艺术
  • Android Studio安装ADB Wi-Fi插件使用WIFI连接终端设备调试程序
  • Java11使用JVM同一日志框架启用日志记录
  • Shire 1.1 发布:更强大的交互支持,升级 AI 智能体与 IDE 的整合体验
  • 【Unity】WebGL全屏问题
  • 在Scala中栈的认识
  • A30 PHP+MYSQL+LW+工厂库存仓储订单销售后台管理系统的设计与实现 源代码 配置 文档
  • ROS2创建 base 包用于其他模块的参数配置和头文件依赖
  • 【计算机网络】实验1:访问WEB服务器
  • DBA面试题-1
  • 【大模型微调】pdf转markdown
  • QT-thread2种方式选择的优劣对比
  • uniapp 生成二维码
  • 量化交易系统开发-实时行情自动化交易-8.9.通达信平台
  • docker部署RustDesk自建服务器
  • 【自用】管材流转项目前端重部署流程 vue2 webpackage4 vuecli4
  • Webpack开发模式及处理样式资源
  • Hyperf jsonrpc
  • 利用 Redisson 实现分布式主键生成
  • echarts 实时 vue 使用方法