不使用 socket.io 来实现原生聊天室
后端
流程
创建项目文件夹
在文件夹目录下执行
npm init初始化package.json文件创建
index.js作为服务器安装 Node.js 的
ws库:npm install ws
代码
js
// 引入WebSocketServer类
const { WebSocketServer } = require("ws");
// 自定义端口号
const PORT = 5000;
// 服务器监听connection事件,有客户端成功连接时触发
wsServer.on("connection", (ws) => {
// 监听消息事件
ws.on("message", (message) => {
console.log("接收消息:", message);
});
// 监听关闭事件
ws.on("close", () => {
console.log("客户端关闭!");
});
// 监听错误事件
ws.on("error", (error) => {
console.log("WebSocket error:", error);
});
});- 运行项目
js
node ./index.js前端
安装 vue2 项目
js
yarn add vue-native-websocket
# or
npm install vue-native-websocket --save代码
- main.js
js
<!--main.js-->
import Vue from 'vue'
import App from './App.vue'
import websocket from 'vue-native-websocket'
Vue.use(websocket, 'ws://10.8.10.103:9090', {// 这里要填的是服务器的地址,可以换一个在线服务器wss://echo.websocket.org
reconnection: true, // (Boolean)是否自动重连,默认false
reconnectionAttempts: 5, // 重连次数
reconnectionDelay: 3000, // 再次重连等待时常(1000)
})
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')组件
vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<section class="center">
<div class="message">{{ msg }}</div>
<div class="input">
<textarea
name
id="text"
cols="30"
rows="2"
v-model.trim="text"
></textarea>
<button class="danger" @click="clear">clear</button>
<button class="green" :disabled="empty" @click="websocketsend">
send
</button>
</div>
</section>
</div>
</template>
<script>
export default {
name: "websocket",
data() {
return {
msg: "",
text: "",
empty: true,
send: true,
};
},
watch: {
text: function (newValue, oldValue) {
newValue.length > 0 ? (this.empty = false) : (this.empty = true);
},
},
methods: {
clear() {
this.text = "";
this.$socket.close();
},
initWebSocket() {
//初始化weosocket,这些onopen是一个事件,当
this.$socket = new WebSocket("http://127.0.0.1:5000");
this.$socket.onopen = this.websocketonopen;
this.$socket.onerror = this.websocketonerror;
this.$socket.onmessage = this.websocketonmessage;
this.$socket.onclose = this.websocketclose;
},
websocketonopen(e) {
// 链接ws服务器,e.target.readyState = 0/1/2/3
//0 CONNECTING ,1 OPEN, 2 CLOSING, 3 CLOSED
console.log("WebSocket连接成功", e);
},
websocketonerror(e) {
//错误
console.log("WebSocket连接发生错误");
console.log(e);
console.log("------------");
},
websocketonmessage(e) {
//数据接收
console.log(e.data);
this.msg = e.data;
},
websocketsend(e) {
//数据发送
this.$socket.send(this.text);
// this.$socket.close(1000)
console.log(this.$socket.readyState); // 当前链接状态 https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket#%E5%B8%B8%E9%87%8F
},
websocketclose(e) {
//关闭链接时触发
var code = e.code; // 状态码表 https://developer.mozilla.org/zh-CN/docs/Web/API/CloseEvent
var reason = e.reason;
var wasClean = e.wasClean;
console.log(code, reason, wasClean);
},
},
created() {
this.initWebSocket();
},
destoryed() {
this.$socket.close();
},
};
</script>