websocket异步变同步
_天天写代码_
2023年02月07日 13:21
收录于文集
共5篇

代码块
JavaScript
自动换行
复制代码
export default class LsWebsocketIO {
    //当前工作目录的绝对路径
    workPath: string = ''
    // 1. 建立连接
    socket: any = null
    // 2. 服务器地址
    url: string = "ws://localhost:10001"
    // 3. 发送消息
    message: string = ""
    // 4. 接收消息
    messages: string[] = []
    actions: string[] = [
        '获取当前工作目录的绝对路径',
        '发送渲染数据'
    ]
    //同步锁
    lock: boolean = false
    //
    response: string = ''
    handle: any = null

    // 1. 建立连接
    connect() {
        this.socket = new WebSocket(this.url)
        this.socket.onmessage = (msg: any)=> {
            console.log('::::::::::检查锁状态', this.lock, msg.data)
            if (this.lock) {
                console.log('::::::::::解锁')
                this.handle(msg.data)
                this.lock = false
                return
            }
            console.info('未处理的消息', msg)
            throw new Error("未处理的消息");


        }
        this.socket.onclose = () => {
            this.messages.push("连接关闭")
        }
        this.socket.onopen = () => {
            this.messages.push("连接成功")
            this.getWorkPath().then(path =>this.workPath = path )

        }


    }


    // 2. 发送消息
    send(message: string) {
        return new Promise((resolve, reject) => {
            if (this.lock) {
                reject('上一次请求还未完成')
            }
            this.lock = true
            this.handle = resolve
            this.socket.send(message)
            console.log('::::::::::上锁',this.lock)
        }).then(message => {
            this.messages.push('发送:' + message)
            return message
        })
    }



    // 3. 关闭连接
    close() {
        this.socket.close()
    }


    //是否连接
    isConnect() {
        if (!this.socket) return false
        return this.socket.readyState === 1
    }

    //获取当前工作目录的绝对路径
    getWorkPath() {
        return this.send('获取当前工作目录的绝对路径')
    }
}
复制成功