前期准备

  1. 由于使用python的flask框架,所以需要python环境以及flaskflask_socketio
1
pip install flask flask_socketio
  1. 前端Socket.IO
1
npm install socket.io-client

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from flask import Flask
# 引入跨域设置
from flask_cors import CORS
# 引入socketio
from flask_socketio import SocketIO
from flask_socketio import send, emit

# 实例化app
app = Flask(__name__)

# 设置跨域
CORS(app)
# 设置socket
socketio = SocketIO(app, cors_allowed_origins='*')


@socketio.on('hello')
def hello(str):
print("接收到的数据为->", str)
emit('respond', f'服务器:我收到了{str}')


@socketio.on('connect', namespace='/')
def connected():
print('Client connect')
emit('response', {'data': 'Connected'})


@socketio.on('disconnect', namespace='/')
def disconnected():
print('Client disconnected')


# 运行主程序
if __name__ == '__main__':
# app.run()
socketio.run(app)

客户端

自定义hooks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// webscoket.ts
import { ref, onMounted, onUnmounted } from "vue";
import { io, Socket } from "socket.io-client";

export default function useSocket(url: string) {
const socket = ref<Socket>();

onMounted(() => {
socket.value = io(url,{
reconnectionAttempts: 5 // 设置最大重连次数为2
});

socket.value.on("connect", () => {
console.log("connect success");
});

socket.value.on("disconnect", () => {
console.log("disconnected from server");
});

// 监听服务器respond返回
socket.value.on("respond", data => {
console.log(data);
// 如果数据等于10,客户端发送关闭连接请求
if (data === 10) {
socket.value?.disconnect();
}
});
});
onUnmounted(() => {
if (socket.value) {
socket.value.disconnect();
}
});
return { socket };
}

使用hooks连接服务器

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<el-button type="primary" size="default" @click="sendHello">问候服务器</el-button>
</template>

<script setup lang="ts">
import useSocket from "@/componse/webscoket";
const { socket } = useSocket("http://127.0.0.1:5000");

const sendHello = () => {
socket.value?.emit("hello", "你好服务器");
};
</script>