import { ref } from 'vue';
 
export default function useWebSocket(url) {
    const messagesData = ref([]);
 
    // 创建WebSocket连接和相关方法
    const socket = new WebSocket(url);
 
    socket.onopen = () => {
        console.log('WebSocket连接已建立');
    };
 
    socket.onmessage = (event) => {
      const receivedMessage = event.data;
      //接收到后端消息，根据业务逻辑自行处理
      console.log('receivedMessage'+ receivedMessage); 
        
    };
 
    socket.onclose = () => {
        console.log('WebSocket连接已关闭');
    };
    return {
        messagesData,
        sendMessage: (message) => {
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(message);
            }
        },
        closeConnection: () => {
            socket.close();
        }
    };
}