通過websocket實(shí)現(xiàn)簡單的聊天室功能
需求分析如圖:
搭建的項(xiàng)目結(jié)構(gòu)如圖:
前端步驟:
- vue create socket_demo (創(chuàng)建項(xiàng)目)
- views下面建立Home , Login組件
- 路由里面配置路徑
- Home組件內(nèi)部開啟websocket連接
前端相關(guān)組件代碼:
Login組件
<!-- Login.vue -->
<template>
<div>
<input type="text" placeholder="請(qǐng)輸入用戶名" v-model="username">
<button @click="enterRoom">進(jìn)入聊天室</button>
</div>
</template>
<script>
export default {
name: 'login',
data() {
return {
username: '',
}
},
methods: {
enterRoom() {
let username = this.username.trim()
if (username.length < 6) {
alert('用戶名小于6位,請(qǐng)重新輸入!')
return
}
// 保存用戶名
localStorage.setItem('username', username)
// 進(jìn)入首頁
this.$router.push('/')
},
}
}
</script>
<style>
</style>
Home組件
<!-- Home.vue -->
<template>
<div>
<ul>
<li v-for="item in msgList" :key="item.id">
<p>
<span>{{item.user}}</span>
<span>{{new Date(item.dateTime)}}</span>
</p>
<p>消息:{{item.msg}}</p>
</li>
</ul>
<input type="text" placeholder="請(qǐng)輸入消息" v-model="msg">
<button @click="sendMsg">發(fā)送</button>
</div>
</template>
<script>
let ws = new WebSocket('ws://localhost:8000')
export default {
name: 'home',
data() {
return {
msg: '',
username: '',
msgList: []
}
},
mounted() {
this.username = localStorage.getItem('username')
if (!this.username) {
this.$router.push('/login')
return
}
ws.onopen = (e) => {
console.log('WebSocket opne ', e);
}
ws.onclose = (e) => {
console.log('WebSocket onclose ', e);
}
ws.onerror = (e) => {
console.log('WebSocket onerror ', e);
}
// 接收服務(wù)端發(fā)送過來的消息
ws.onmessage = (e) => {
// console.log('WebSocket onmessage ', e);f
let msg = JSON.parse(e.data)
// console.log('msg', msg);
this.msgList.push(msg)
}
},
methods: {
// 發(fā)送消息
sendMsg() {
if (!this.msg) {
return
}
let obj = {
id: Math.floor(Math.random() * 100),
user: this.username,
dateTime: new Date().getTime(),
msg: this.msg
}
ws.send(JSON.stringify(obj))
this.msg = ''
},
}
}
</script>
<style>
</style>
router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/',
name: 'home',
component: () => import('../views/Home.vue')
}
]
const router = new VueRouter({
routes,
mode: 'history'
})
export default router
后端步驟:
- 在項(xiàng)目外層創(chuàng)建server文件夾(src目錄同級(jí))
- npm init -y創(chuàng)建安裝包
- npm i ws (安裝websocket的插件ws)
- index.js 文件內(nèi)部開啟服務(wù),初始化相關(guān)事件
后端服務(wù)的啟動(dòng):server下面建立index.js文件,package.json里面配置命令,npm run dev啟動(dòng)
index.js文件文章來源:http://www.zghlxwxcb.cn/news/detail-814980.html
const Ws = require('ws');
((Ws) => {
// 開啟服務(wù)
const server = new Ws.Server({
host: 'localhost',
port: 8000
})
const init = () => {
bindEvent()
}
// 初始化相關(guān)事件
function bindEvent() {
server.on('open', handleOpen)
server.on('close', handleClose)
server.on('error', handleError)
server.on('connection', handleConnection)
}
function handleOpen() {
console.log('websocket open');
}
function handleClose() {
console.log('websocket Close');
}
function handleError() {
console.log('websocket Error');
}
function handleConnection(ws) {
console.log('websocket Connection');
ws.on('message', handleMessage)
}
function handleMessage(msg) {
// console.log('msg', msg.toString());
let message = msg.toString()
// 獲取所有和服務(wù)端連接的客戶端,并向它們推送消息
server.clients.forEach(c => {
c.send(message)
})
}
init()
})(Ws);
效果圖:文章來源地址http://www.zghlxwxcb.cn/news/detail-814980.html
到了這里,關(guān)于websocket實(shí)現(xiàn)聊天室(vue2 + node)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!