- 背景:老板想要封装一个前端socket,包含功能:跟服务器连接上+保持心跳 + 收发消息。
- 本前端笨蛋的苦恼点:服务端没介入,我咋测试?搜了大佬们的文章,都没搜到咋个自己当服务器测试的,于是本机当socket服务就来了...
1. 本机启动socket服务器
- 有node环境
- 有ws环境:npm install ws
- 本地编写websocket-server.js文件,文件内容如下:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
console.log('server is running on ws://localhost:8080');
- 运行websocket-server.js文件:node websocket-server.js。运行完成后会生成socket服务地址:ws://localhost:8080
2、前端运行socket
1、创建socket.vue文件
<template>
<div>
<h1>来吧试试webSoket</h1>
<input v-model="message" @keyup.enter="sendMessage" placeholder="请输入想要发送给服务器的信息" />
<ul>
<li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
</ul>
<el-button @click="disconnect">断开soket连接</el-button>
</div>
</template>
<script>
export default {
data ()
{
return {
socket: null,
message: "",
messages: [],
heartbeatInterval: null,
heartbeatTimeout: null,
heartbeatDelay: 5000, // 心跳间隔
reconnectDelay: 3000, // 重连间隔
};
},
created ()
{
this.connect();
},
beforeDestroy ()
{
this.disconnect();
},
methods: {
connect ()
{
const url = "ws://localhost:8080"; // 修改本机的WebSocket服务器地址
this.socket = new WebSocket( url );
this.socket.onopen = () =>
{
// 监听socket连接,连接成功则执行该函数
console.log( "WebSocket Connected" );
this.startHeartbeat();
};
this.socket.onmessage = ( event ) =>
{
console.log( "Message from server ", event.data );
this.messages.push( event.data );
};
this.socket.onerror = ( error ) =>
{
// 监听socket错误信息
console.error( "WebSocket Error: ", error );
this.reconnect();
};
this.socket.onclose = () =>
{
// 监听socket连接关闭
console.log( "WebSocket Connection Closed" );
this.reconnect();
};
},
sendMessage ()
{
if ( this.socket.readyState === WebSocket.OPEN )
{
this.socket.send( this.message );
this.message = "";
} else
{
console.error( "WebSocket is not connected." );
}
},
disconnect ()
{
if ( this.socket )
{
this.socket.close();
this.stopHeartbeat();
}
},
reconnect ()
{
setTimeout( () =>
{
this.connect();
}, this.reconnectDelay );
},
startHeartbeat ()
{
this.heartbeatInterval = setInterval( () =>
{
if ( this.socket.readyState === WebSocket.OPEN )
{
this.socket.send( JSON.stringify( { type: "ping" } ) ); // 发送心跳消息
this.resetHeartbeatTimeout();
}
}, this.heartbeatDelay );
this.heartbeatTimeout = setTimeout( () =>
{
// 如果心跳超时,则关闭连接
this.disconnect();
}, this.heartbeatDelay * 2 );
},
resetHeartbeatTimeout ()
{
clearTimeout( this.heartbeatTimeout );
this.heartbeatTimeout = setTimeout( () =>
{
this.disconnect();
}, this.heartbeatDelay * 2 );
},
stopHeartbeat ()
{
clearInterval( this.heartbeatInterval );
clearTimeout( this.heartbeatTimeout );
},
},
};
</script>
<style scoped>
/* 添加你的样式 */
</style>
2、运行后的效果如下:控制台打印这句话说明连接本机成功啦。
3、在浏览器输入框中输入你想发送的消息,敲回车
4、就可以在vscode控制台接收到你发送的消息,如下所示: