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

 更新时间:2024年12月04日 11:28:18   作者:前端青山  
随着 Web 技术的发展,实时通信成为现代 Web 应用的重要组成部分,Socket.IO 是一个流行的库,支持及时、双向与基于事件的通信,适用于各种平台和设备,本文将介绍如何在 Vue.js 项目中集成 Socket.IO,实现一个简单的实时聊天应用,需要的朋友可以参考下

前言

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

1. socket.io

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

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

在这里插入图片描述

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>

总结

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

以上就是Vue.js中集成Socket.IO实现实时聊天功能的详细内容,更多关于Vue Socket.IO实时聊天的资料请关注脚本之家其它相关文章!

相关文章

  • vue3中<script setup> 和 setup函数的区别对比

    vue3中<script setup> 和 setup函数的区别对比

    这篇文章主要介绍了vue3中<script setup> 和 setup函数的区别,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-04-04
  • Vue父子组建的简单通信之控制开关Switch的实现

    Vue父子组建的简单通信之控制开关Switch的实现

    这篇文章主要介绍了Vue父子组建的简单通信之控制开关Switch的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • vue实现At人文本输入框示例详解

    vue实现At人文本输入框示例详解

    这篇文章主要为大家介绍了vue实现At人文本输入框示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • vue中自定义组件双向绑定的三种方法总结

    vue中自定义组件双向绑定的三种方法总结

    这篇文章主要介绍了vue中自定义组件双向绑定的三种方法总结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • Python实现图片二值化的详细代码

    Python实现图片二值化的详细代码

    图像二值化就是将图像上的像素点的“灰度值”设置为[0, 0, 0]或[255, 255, 255],即要么纯黑,要么纯白,这篇文章主要介绍了Python实现图片二值化,需要的朋友可以参考下
    2024-05-05
  • vue中如何使用ztree

    vue中如何使用ztree

    这篇文章主要介绍了vue中如何使用ztree,包括配置package.json,自动加载jquery的方法,本文给大家介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下
    2018-02-02
  • 详解Vue2 SSR 缓存 Api 数据

    详解Vue2 SSR 缓存 Api 数据

    本篇文章主要介绍了Vue2 SSR 缓存 Api 数据,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11
  • Vue中使一个div铺满全屏的实现

    Vue中使一个div铺满全屏的实现

    最近在项目开发中,就遇到了这个问题,Vue中如何使一个div铺满全屏,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-07-07
  • vue2实现简易时钟效果

    vue2实现简易时钟效果

    这篇文章主要为大家详细介绍了vue2实现简易时钟效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • Vue配置代理(devServer)解决跨域问题

    Vue配置代理(devServer)解决跨域问题

    这篇文章主要介绍了Vue配置代理(devServer)解决跨域问题,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-08-08

最新评论