跳至主要內容
vue2使用websocket

vue代码

<template>
    <div>
        <div style="display: flex;justify-content: center;align-items: center;">
            <button @click="btnClick">发送</button>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            ws: null,
            WebSocketUrl: 'ws://localhost:7777/websocket/1',
        }
    },
    created() {
        this.handleConnect()
    },
    destroyed() {
        this.handleExit()
    },
    methods: {
        handleConnect() {
            this.ws = new WebSocket(this.WebSocketUrl)
            this.ws.onmessage = (e) => {
                console.log(e)
            }
            this.ws.onclose = () => {
                console.log('连接关闭')
            }
        },
        handleExit() {
            if (this.ws) {
                this.ws.close()
                this.ws = null
            }
        },
        btnClick() {
            this.ws.send('test')
        },
    }
}

</script>

<style scoped></style>

荒芜...小于 1 分钟前端vue2websocket
SpringBoot集成websocket并测试使用

集成websocket

引入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

荒芜...大约 2 分钟javaSpringBootwebsocket