Vue实时通信 实现用webSocket长连接聊天功能
1.安装vue-cli 2.init 初始化项目 3.npm install ws(websocket) 4.文件夹中创建server.js
1、服务器代码
const http = require('http').createServer();
const express = require('express')
var webSocket = require('ws')
var wss = new webSocket.Server({port:3000})
wss.on("connection",function(ws){
console.log("新用户连接")
ws.on("message",function(data){
wss.clients.forEach(function(client){
client.send(data)
})
})
})
console.log('server is running...')
2、客户端页面代码
<template>
<div class="home">
<ul>
<li v-for="item in msgList" :key="item.id">
<p>消息:{{item.msg}}</p>
</li>
</ul>
<input type="text" placeholder="在此输入消息" v-model="msg">
<button @click="sendMessage()">发送</button>
</div>
</template>
<script src="../scripts/socket.io.js"></script>
<script>
const ws = new WebSocket("ws://localhost:3000");
export default {
data() {
return {
msg: '',
msgList: []
}
},
mounted() {
ws.addEventListener("open", (e) => {
console.log(e);
});
ws.addEventListener('close', (e) => {
console.log(e);
})
ws.addEventListener('error', (e) => {
console.log(e);
})
ws.addEventListener('message', (e) => {
let self = this;
const msg = JSON.parse(e.data)
self.msgList.push(msg)
console.log(self.msgList);
})
},
methods: {
sendMessage() {
let self = this;
ws.send(JSON.stringify({
msg: self.msg
}))
self.msg = ''
},
},
};
</script>
|