ExerciseOCR/test.html

133 lines
4.4 KiB
HTML
Raw Normal View History

2024-10-25 12:53:51 +00:00
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket 文本和图片接收器</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-plus/dist/index.css">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f4;
}
#app {
width: 100%;
max-width: 600px;
padding: 20px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
background-color: white;
border-radius: 8px;
}
.el-textarea__inner {
min-height: 150px;
resize: vertical;
}
.el-row {
margin-bottom: 20px;
}
.image-container {
text-align: center;
margin-bottom: 20px;
}
img {
max-width: 100%;
border-radius: 8px;
}
@media (max-width: 600px) {
#app {
width: 90%;
padding: 10px;
}
}
</style>
</head>
<body>
<div id="app">
<div class="image-container" v-if="imageUrl">
<img :src="imageUrl" alt="Received Image">
</div>
<el-row>
<el-col :span="24">
<el-input
v-model="text"
type="textarea"
:rows="4"
readonly
placeholder="接收到的文本将显示在这里..."
></el-input>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-button type="primary" @click="copyText">复制</el-button>
<el-button type="danger" @click="clearText">清空</el-button>
</el-col>
</el-row>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@3"></script>
<script src="https://cdn.jsdelivr.net/npm/element-plus"></script>
<script>
const { createApp } = Vue;
const { ElInput, ElButton, ElRow, ElCol, ElMessage } = ElementPlus;
createApp({
data() {
return {
text: '',
imageUrl: '',
websocket: null,
reconnectInterval: 10000,
uri: "ws://localhost:8000/event"
};
},
mounted() {
this.connectWebSocket();
},
methods: {
connectWebSocket() {
this.websocket = new WebSocket(this.uri);
this.websocket.onopen = () => {
console.log("已连接到服务器。等待接收消息...");
};
this.websocket.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === 'text') {
this.text += data.content; // + '\n';
} else if (data.type === 'image') {
this.imageUrl = `data:image/jpeg;base64,${data.content}`;
this.text = '';
}
};
this.websocket.onclose = () => {
console.log("服务器关闭了连接。10秒后重新连接...");
setTimeout(() => {
this.connectWebSocket();
}, this.reconnectInterval);
};
this.websocket.onerror = (error) => {
console.error("WebSocket 错误:", error);
this.websocket.close();
};
},
copyText() {
navigator.clipboard.writeText(this.text).then(() => {
ElMessage.success('文本已复制到剪贴板');
}).catch((error) => {
ElMessage.error('复制文本失败: ' + error);
});
},
clearText() {
this.text = '';
this.imageUrl = '';
}
}
}).use(ElementPlus).mount('#app');
</script>
</body>
</html>