1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
|
import { reactive } from "vue" import { io, Socket } from "socket.io-client"
class SocketService { socket: Socket state: any
constructor() { this.state = reactive({ id: "", room: "", sio: null, flag: 60, sid: "", heartbeatTimer: null })
this.socket = io("/websocket", { autoConnect: false, extraHeaders: { "Access-Control-Allow-Origin": "*" } })
this.socket.once("connect", () => { this.handleConnect() })
this.socket.once("get_sid", (data) => { this.handleGetSid(data) })
this.socket.on("join_room_result", (res) => { this.handleJoinRoomResult(res) })
this.socket.on("test", (data) => { this.handleTest(data) })
this.socket.on("leave", (room) => { this.handleLeave(room) })
this.socket.on("leave_all", () => { this.handleLeaveAll() })
this.socket.on("connect_error", (err) => { this.handleConnectError(err) }) }
connect() { this.socket.connect() console.log("socket connect") }
disconnect() { this.handleLeaveAll() this.stopHeartbeat() this.socket.disconnect() console.log("socket disconnect") }
joinRoom(room: string) { this.socket.emit("join", { rooms: [room] }) }
leaveRoom(room: string) { this.handleLeave(room) }
leaveAll() { this.handleLeaveAll() }
private handleConnect() { this.socket.emit("get_sid", {}) }
private handleGetSid(data: any) { this.state.sid = data.sid console.log("get_sid:", this.state.sid) }
private handleJoinRoomResult(res: any) { console.log(res) }
private handleTest(data: any) { console.log("test data:" + data) }
private handleLeave(room: string) { this.socket.emit("leave", { rooms: [room] }) console.log("leave room " + room) }
private handleLeaveAll() { this.socket.emit("leave_all") console.log("leave all room") }
private handleConnectError(err: any) { this.stopHeartbeat() console.log(err) } private startHeartbeat() => { if(this.heartbeatTimer === null) { this.heartbeatTimer = setInterval(() => { this.sendHeartbeat() }, 15000) } }
private stopHeartbeat() => { if(this.heartbeatTimer !== null) { clearInterval(this.heartbeatTimer) this.heartbeatTimer = null } }
private sendHeartbeat() { this.socket.emit("heartbeat", { }) } }
export const socketService = new SocketService() export const socket = socketService.socket export const state = socketService.state
|