介绍如何使用 Vite、Vue 3 和 Node.js 开发一个简单的聊天室。
创建项目
- 在命令提示符下输入
npm init vite@latest chatroom -- --template vue
以创建项目。 - 打开
chatroom
项目文件夹。 - 运行
npm install
安装必要的依赖项。 - 安装完之后,运行
npm run dev
就可以看到默认的画面。
设计界面
打开 src 文件夹中的 App.vue 文件,开始设计你想要的样式。
也可以参考以下代码:
<template>
<div class="chat-container">
<div class="chat-title">Chatroom</div>
<div class="chat-window">
<div class="messages">
<div class="message-bubble sent">How are you?</div>
<div class="message-bubble received">I'm excellent!</div>
<div class="message-bubble sent">What about you?</div>
<div class="message-bubble received">Doing great, thanks!</div>
</div>
<input
class="message-input"
placeholder="Type your message here..."
/>
</div>
</div>
</template>
<style scoped>
.chat-container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
height: calc(100vh - 4rem);
background-color: #f5f0e6;
}
.chat-title {
width: 100%;
text-align: center;
font-size: 24px;
font-weight: bold;
margin-bottom: 1rem;
}
.chat-window {
width: 400px;
height: 75vh;
background-color: rgba(255, 255, 255, 0.85);
border-radius: 15px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
display: flex;
flex-direction: column;
}
.messages {
flex-grow: 1;
margin-bottom: 20px;
overflow-y: scroll;
padding-right: 10px;
display: flex;
flex-direction: column;
}
.message-bubble {
border-radius: 10px;
padding: 10px;
margin-bottom: 10px;
max-width: 70%;
word-wrap: break-word;
}
.sent {
background-color: #e6ccb2;
align-self: flex-end;
text-align: right;
}
.received {
background-color: #d1e7dd;
align-self: flex-start;
text-align: left;
}
.message-input {
padding: 15px;
font-size: 16px;
border: none;
border-radius: 10px;
background-color: #f0e2d0;
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
width: 100%;
box-sizing: border-box;
outline: none;
}
.message-input:focus {
box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.2);
}
</style>
设置 WebSocket 连接
- 输入
npm install vue-socket.io socket.io-client
,安装所需的 Socket.IO 和 Vue 插件。
(Socket.IO 是负责与 Socket.IO 服务器通信的官方客户端库。它提供所有 WebSocket 相关功能,如连接、断开连接、发送和接收事件等。)
- 打开 src/main.ts,配置以下代码:
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { io } from "socket.io-client";
// Establish a WebSocket connection.
const socket = io('http://localhost:3000');
const app = createApp(App);
// Provide the socket instance directly to the entire application.
app.provide('socket', socket);
app.mount('#app');
- 打开
src/App.vue
并配置以下代码:
<template>
<div class="chat-container">
<div class="chat-title">Chatroom</div>
<div class="chat-window">
<div class="messages">
<div
v-for="(message, index) in messages"
:key="index"
:class="['message-bubble', message.type]"
>
{{ message.text }}
</div>
</div>
<input
v-model="newMessage"
@keyup.enter="sendMessage"
class="message-input"
placeholder="Type your message here..."
/>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, inject } from "vue";
import { Socket } from "socket.io-client"; // Import the Socket type
// Define message state
const messages = ref<{ text: string; type: string }[]>([]);
const newMessage = ref<string>("");
// Inject socket instance
const socket = inject<Socket>("socket"); // Specify the type of socket
if (!socket) {
throw new Error("Socket instance is not provided");
}
// Receive messages from the server when the component is mounted
onMounted(() => {
socket.on("message", (msg: string) => {
messages.value.push({ text: msg, type: "received" });
});
});
// Send messages to the server
const sendMessage = () => {
if (newMessage.value.trim()) {
socket.emit("message", newMessage.value);
messages.value.push({ text: newMessage.value, type: "sent" });
newMessage.value = "";
}
};
</script>
创建 WebSocket 服务器
- 创建名为
chatroom-server
的文件夹。 - 在 VSCode 中打开
chatroom-server
文件夹,运行npm init -y
创建一个 Node.js 项目(“-y ”标志会自动跳过所有问题,并生成一个包含默认值的 package.json 文件)。 - 运行
npm install cors
安装 CORS 软件包(CORS 是用于处理跨源请求的中间件)。 - 运行
npm install socket.io
安装 Socket.IO。 - 运行
npm install express
安装 Express(用于构建 Web 应用程序和 API)。 - 在该目录下创建一个名为 server.js 的新文件,编写 WebSocket 服务器的代码,并配置 CORS 以避免在测试过程中出现跨源问题。
- 完成后,运行
node server.js
,查看 WebSocket 服务器是否已启动并在 ws://localhost:3000 处运行。
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors');
// Create Express application
const app = express();
// Configure CORS
app.use(cors({
origin: 'http://127.0.0.1:5173', // Allowed frontend address
methods: ['GET', 'POST'], // Allowed HTTP methods
credentials: true // Allow sending cookies and other credentials
}));
// Create HTTP server
const server = http.createServer(app);
// Create WebSocket server
const io = new Server(server, {
cors: {
origin: 'http://127.0.0.1:5173', // Allowed frontend address
methods: ['GET', 'POST'] // Allowed HTTP methods
}
});
// Handle client connection
io.on('connection', (socket) => {
console.log('A new client connected');
// When a message is received, broadcast it to other clients
socket.on('message', (message) => {
console.log(`Received: ${message}`);
io.emit('message', message); // Broadcast message
});
// Handle client disconnection
socket.on('disconnect', () => {
console.log('A client disconnected');
});
});
// Start the server
server.listen(3000, () => {
console.log('WebSocket server is running on http://localhost:3000');
});
完成
作者:Vic
本文来自作者投稿,版权归原作者所有。如需转载,请注明出处:https://www.nxrte.com/jishu/im/52658.html