Socket.io 是一个基于 WebSocket 的实时通信库,它支持双向通信的适用于多种场景,如聊天室、游戏、数据监控等。在前端开发中,我们通常会用到 Vue.js 这样的前端框架,而在 Vue 应用中集成 Socket.io,实现实时通信,也是一个非常有意义的技术探索。
前提条件
在我们开始前,需要确保以下几个前提条件:
- 熟悉 Vue.js 框架和基本语法;
- 了解 Socket.io 的基本用法;
- 搭建好 Node.js 环境,并安装好 Socket.io 和 Vue.js。
第一步:搭建后端服务
在项目中添加一个后端服务,主要用于监听客户端的 Socket 连接请求,实现 Socket 的实时通信。我们可以通过以下命令,安装 socket.io 和 express:
npm install --save socket.io express
接着,我们在后端服务中添加以下代码:
// www.javascriptcn.com code example
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
// 创建 HTTP 服务器,将 Express 应用程序作为回调函数传入
const server = http.createServer(app);
// 创建服务器端的 Socket.io 实例
const io = socketIo(server);
// 用户列表
let userList = [];
// 监听客户端连接事件
io.on('connection', (socket) => {
console.log('客户端已连接');
// 监听客户端发送的信息
socket.on('message', (data) => {
console.log('客户端发送:', data);
// 将信息广播给所有客户端
io.emit('message', data);
});
// 监听客户端发送的登录请求
socket.on('login', (data) => {
console.log('客户端提交用户信息:', data);
// 将用户信息添加到用户列表
userList.push(data);
// 将用户列表以及当前登录用户信息广播给所有客户端
io.emit('login', { userList, user: data });
});
// 监听客户端发送的注销请求
socket.on('logout', (data) => {
console.log('客户端注销用户信息:', data);
// 将用户信息从用户列表中移除
userList = userList.filter((item) => item.userId !== data.userId);
// 将用户列表以及当前注销用户信息广播给所有客户端
io.emit('logout', { userList, user: data });
});
// 监听客户端断开连接事件
socket.on('disconnect', () => {
console.log('客户端已断开');
});
});
// 将服务器绑定在指定端口
server.listen(3000, () => {
console.log('Server Start!');
});这里,我们使用 express 框架,创建一个 HTTP 服务器,并将其作为 socket.io 的回调函数传入,用于监听客户端的连接请求,并实现 Socket 的实时通信。其中,我们使用 userList 数组来存储当前在线的用户信息。
此时,我们的后端服务就可以实现 Socket 的实时通信了,接下来,我们就要开始搭建前端项目,并在其中集成 Socket.io。
第二步:搭建前端项目
在项目中添加一个前端项目,通过 Vue.js 框架的脚手架工具,快速搭建一个基本的 Vue.js 应用程序,并安装 socket.io-client。
npm install --save socket.io-client
创建一个 Vue.js 组件 Chat.vue,如下所示:
// www.javascriptcn.com code example
<template>
<div>
<h1>欢迎来到聊天室</h1>
<div class="user-box">
<h3>当前在线用户</h3>
<ul>
<li v-for="(item, index) in userList" :key="index">
{{ item.name }}
</li>
</ul>
</div>
<div class="chat-box">
<h3>消息列表</h3>
<ul>
<li
v-for="(item, index) in messageList"
:key="index"
:class="{ send: item.userId === user.userId }"
>
<span>{{ item.name }}</span>[{{ item.time }}]{{ item.content }}
</li>
</ul>
<div class="chat-input">
<input type="text" v-model="messageInput" placeholder="请输入消息" />
<button @click="sendMessage">发送</button>
</div>
</div>
</div>
</template>
<script>
import io from 'socket.io-client';
export default {
name: 'Chat',
data() {
return {
userList: [],
user: {
userId: 'user_' + Date.now(),
name: '',
},
messageList: [],
messageInput: '',
};
},
created() {
// 连接服务器
this.socket = io('http://localhost:3000');
// 监听服务器发送的信息
this.socket.on('message', (data) => {
this.messageList.push(data);
});
// 监听服务器发送的用户列表
this.socket.on('login', (data) => {
this.userList = data.userList;
this.user = data.user;
this.messageList.push({
userId: this.user.userId,
name: this.user.name,
time: this.getTime(),
content: `欢迎 ${this.user.name} 加入聊天室`,
});
});
// 监听服务器发送的用户注销信息
this.socket.on('logout', (data) => {
this.userList = data.userList;
this.messageList.push({
userId: data.user.userId,
name: data.user.name,
time: this.getTime(),
content: `${data.user.name} 离开了聊天室`,
});
});
},
methods: {
getTime() {
let now = new Date();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
return `${hour}:${minute}:${second}`;
},
sendMessage() {
if (!this.messageInput) {
return;
}
const message = {
userId: this.user.userId,
name: this.user.name,
time: this.getTime(),
content: this.messageInput,
};
this.messageList.push(message);
this.socket.emit('message', message);
this.messageInput = '';
},
},
};
</script>
<style scoped>
.user-box {
width: 200px;
float: left;
}
.user-box ul {
margin: 0;
padding: 0;
list-style: none;
}
.user-box li {
margin: 20px 0;
font-size: 18px;
}
.chat-box {
margin-left: 220px;
}
.chat-box ul {
margin: 0;
padding: 0;
list-style: none;
height: 500px;
overflow-y: auto;
}
.chat-box li {
margin: 10px 0;
padding: 10px;
font-size: 16px;
border-radius: 5px;
}
.chat-box li.send {
background-color: #eee;
text-align: right;
}
.chat-input {
margin-top: 20px;
text-align: right;
}
.chat-input input[type='text'] {
padding: 6px 12px 6px 12px;
border-radius: 3px;
border: 1px solid #e1e1e1;
font-size: 14px;
outline: none;
}
.chat-input button {
margin-left: 10px;
padding: 6px 12px 6px 12px;
border-radius: 3px;
border: none;
background-color: #1c7cd6;
color: #fff;
font-size: 14px;
cursor: pointer;
}
.chat-input button:hover {
background-color: #1a6eb3;
}
</style>在 Chat.vue 组件中,我们通过 socket.io-client 连接到后端服务,同时在 created 钩子函数中监听 Socket 的连接事件、消息事件、登录事件和注销事件。当后端服务向前端发送消息和用户列表时,Chat.vue 组件会自动监听到这些事件,更新 UI 界面,从而实现实时通信的效果。
结语
到这里,我们的 Vue.js 应用程序已经成功集成了 Socket.io,实现了实时通信的目标。通过本文的实践,相信大家已经对 Socket.io 的使用有了更深入的了解,同时对 Vue.js 的应用也更加熟悉。当然,Socket.io 的使用场景还可以有很多,例如实时监控、在线游戏等等,感兴趣的读者可以继续探索。
示例代码已经上传到了Github上,同学们可以参考:https://github.com/openailab/vue-socket.io-chat。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/679333b3504e4ea9bd753c75