WebSocket原生实现
WebSocket-Vue2
WebSocket-Vue3
Vue2版本实现
前端实现
- 目录结构
- login.vue 登录
<template>
<div>
<input type="text" placeholder="请输入用户名" v-model="userInfo.userName">
<input type="text" placeholder="请输入密码" v-model="userInfo.passWord">
<button @click="loginChat">进入聊天室</button>
</div>
</template>
<script>
export default {
name: 'Login',
data () {
return {
userInfo: {
userName: '',
passWord: ''
}
}
},
mounted () {
},
methods: {
loginChat () {
console.log('userInfo', this.userInfo)
// 做一些校验
if (this.userInfo.userName === '' || this.userInfo.passWord === '') {
return alert('用户名和密码为空')
}
localStorage.setItem('userName', this.userInfo.userName)
this.$router.push('/home')
}
}
}
</script>
<style lang="less" scoped>
</style>
- home.vue 聊天室
<template>
<div>
<div>
<ul>
<li v-for="(item, index) in msgList" :key="index">
<p>
<span>{{item.user}}</span>
<span>{{new Date(item.dateTime)}}</span>
</p>
<p>{{item.msg}}</p>
</li>
</ul>
</div>
<hr>
<input type="text" placeholder="请输入消息" v-model="msg">
<button @click="handleSendMsg">发送</button>
</div>
</template>
<script>
const ws = new WebSocket('ws:localhost:8000')
export default {
name: 'home',
data () {
return {
msg: '',
msgList: [],
userName: ''
}
},
mounted () {
this.bindEvent()
this.userName = localStorage.getItem('userName')
if (!this.userName) {
this.$router.push('/login')
}
},
methods: {
handleSendMsg () {
if (!this.msg.trim().length) {
return alert('不能发送空消息')
}
ws.send(JSON.stringify({
user: this.userName,
msg: this.msg,
dateTime: new Date()
}))
},
bindEvent () {
console.log('绑定事件')
ws.addEventListener('close', this.handleClose.bind(this), false)
ws.addEventListener('open', this.handleOpen.bind(this), false)
ws.addEventListener('error', this.handleError.bind(this), false)
ws.addEventListener('message', this.handleMessage.bind(this), false)
},
handleOpen () {
console.log('open')
},
handleClose () {
console.log('close')
},
handleError () {
console.log('error')
},
handleMessage ({data}) {
console.log('message', data)
this.msgList.push(JSON.parse(data))
}
}
}
</script>
<style lang="less" scoped>
</style>
后台实现
-
目录结构
-
index.js
const Ws = require('ws').Server
;((Ws) => {
// ws:localhost:8000
const server = new Ws({
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 (ws) {
console.log('server open')
}
function handleClose (ws) {
console.log('server close')
}
function handleError (ws) {
console.log('server error')
}
function handleConnection (ws) {
console.log('server connection')
ws.on('message', handleMessag)
}
function handleMessag (msg) {
console.log('msg', msg.toString())
// 给所以客户端发送消息
server.clients.forEach(c => {
c.send(msg.toString())
})
console.log(server.clients)
}
init()
})(Ws)