|
@@ -0,0 +1,75 @@
|
|
|
+<template>
|
|
|
+ <div>
|
|
|
+ Welcome<br />
|
|
|
+ <input id="text" type="text" v-model="messageInput" />
|
|
|
+ <div>
|
|
|
+ <button @click="send">send</button>
|
|
|
+ <button @click="closeWebSocket">close</button>
|
|
|
+ </div>
|
|
|
+ <div id="message">
|
|
|
+ <div>
|
|
|
+ <span>倒计时:</span>
|
|
|
+ <p>你输入的内容是:{{ messages }}</p>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ </template>
|
|
|
+
|
|
|
+ <script setup>
|
|
|
+ import { ref, onBeforeUnmount, onMounted } from 'vue'
|
|
|
+
|
|
|
+ const websocket = ref(null)
|
|
|
+ let messages = ref('')
|
|
|
+ const messageInput = ref('')
|
|
|
+
|
|
|
+ onMounted(() => {
|
|
|
+ if ('WebSocket' in window) {
|
|
|
+ websocket.value = new WebSocket('ws://localhost:9999/client/mio')
|
|
|
+
|
|
|
+ websocket.value.onerror = () => {
|
|
|
+ setMessageInnerHTML('error')
|
|
|
+ }
|
|
|
+
|
|
|
+ websocket.value.onopen = () => {
|
|
|
+ setMessageInnerHTML('open')
|
|
|
+ }
|
|
|
+
|
|
|
+ websocket.value.onmessage = (event) => {
|
|
|
+ setMessageInnerHTML(event.data)
|
|
|
+ }
|
|
|
+
|
|
|
+ websocket.value.onclose = () => {
|
|
|
+ setMessageInnerHTML('close')
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ alert('Not support websocket')
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ onBeforeUnmount(() => {
|
|
|
+ if (websocket.value) {
|
|
|
+ websocket.value.close()
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ function setMessageInnerHTML(innerHTML) {
|
|
|
+ messages.value = innerHTML
|
|
|
+ }
|
|
|
+
|
|
|
+ function closeWebSocket() {
|
|
|
+ if (websocket.value) {
|
|
|
+ console.log('关闭连接')
|
|
|
+ websocket.value.close()
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ function send() {
|
|
|
+ if (websocket.value && messageInput.value) {
|
|
|
+ websocket.value.send(messageInput.value)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ </script>
|
|
|
+
|
|
|
+ <style scoped>
|
|
|
+ </style>
|
|
|
+
|