1.思路
新建两个项目:
第一个前端项目,搭建聊天室页面,同时使用Websocket API,与服务端进行通信
第二个项目,使用node环境,下载ws包,搭建服务
年前就发现下包有问题,年后老淘宝镜像已经崩了,完全用不了,现在改https://registry.npmmirror.com
2.前端代码
html
<template>
<div class="container">
<div class="messageBox"></div>
<textarea class="message"></textarea>
<button class="send">发送</button>
</div>
</template>
<script>
export default {
name: 'weChat',
data () {
return {
}
},
mounted () {
this.initWeChat()
},
computed: {
},
methods: {
initWeChat () {
const messageBox= document.querySelector('.messageBox')
const textarea = document.querySelector('.message')
const sendButton = document.querySelector('.send')
// 生成WebSocket对象
const ws = new WebSocket('ws://'改成你的ip':9001/ws')
// 为WebSocket添加事件监听
ws.addEventListener('message', function (event) {
const div = document.createElement('div')
const time = this.getTime()
div.innerText = event.data+''+time
messageBox.append(div)
})
ws.addEventListener('open', () => {
alert('websocket连接建立完毕')
})
sendButton.addEventListener('click', () => {
// 发送消息
ws.send(textarea.value)
})
},
getTime () {
const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, '0')
const day = String(now.getDate()).padStart(2, '0')
const hour = String(now.getHours()).padStart(2, '0')
const min = String(now.getMinutes()).padStart(2, '0')
const second = String(now.getSeconds()).padStart(2, '0')
return `${year}-${month}-${day} ${hour}-${min}-${second}`
}
}
}
</script>
<style lang='scss' scoped>
//样式自己写去吧
</style>
3.node服务
javascript
// 导入WebSocket模块:
const WebSocket = require('ws')
// 引用Server类:
const WebSocketServer = WebSocket.Server
// 实例化:
const wss = new WebSocketServer({
port: 9001,
path: '/ws'
})
const wsList = []
// 监听创建连接事件,回调函数的参数是创建的连接
wss.on('connection', function connection (ws) {
ws.on('error', console.error)
// 监听该连接的接收信息事件
ws.on('message', function message (data) {
console.log('接收到信息: %s', data)
for (const w of wsList) {
if (w.readyState == w.OPEN) {
w.send(data.toString())
}
}
})
wsList.push(ws)
})
//node wechat.js 启动服务