通过websocket实现简单的聊天室功能
需求分析如图:
搭建的项目结构如图:
前端步骤:
- vue create socket_demo (创建项目)
- views下面建立Home , Login组件
- 路由里面配置路径
- Home组件内部开启websocket连接
前端相关组件代码:
Login组件
<!-- Login.vue -->
<template><div><input type="text" placeholder="请输入用户名" v-model="username"> <button @click="enterRoom">进入聊天室</button></div>
</template><script>
export default {name: 'login',data() {return {username: '',}},methods: {enterRoom() {let username = this.username.trim()if (username.length < 6) {alert('用户名小于6位,请重新输入!')return}// 保存用户名localStorage.setItem('username', username)// 进入首页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="请输入消息" v-model="msg"> <button @click="sendMsg">发送</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);}// 接收服务端发送过来的消息ws.onmessage = (e) => {// console.log('WebSocket onmessage ', e);flet msg = JSON.parse(e.data)// console.log('msg', msg);this.msgList.push(msg)}},methods: {// 发送消息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
后端步骤:
- 在项目外层创建server文件夹(src目录同级)
- npm init -y创建安装包
- npm i ws (安装websocket的插件ws)
- index.js 文件内部开启服务,初始化相关事件
后端服务的启动:server下面建立index.js文件,package.json里面配置命令,npm run dev启动
index.js文件
const Ws = require('ws');((Ws) => {// 开启服务const server = new Ws.Server({host: 'localhost',port: 8000})const init = () => {bindEvent()}// 初始化相关事件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()// 获取所有和服务端连接的客户端,并向它们推送消息server.clients.forEach(c => {c.send(message)})}init()
})(Ws);
效果图: