useSocket
Manage a WebSocket connection with auto-reconnection, heartbeat, and message-type-based subscriptions.
⚡Feature
- Auto connect on mount and disconnect on unmount.
- Built-in reconnection with exponential backoff.
- Built-in heartbeat with ping/pong and timeout detection.
- Subscribe to messages by
body.typeor receive all messages viaonMessage. - Manage
status,dataanderrorstate.
Basic Usage
import { useSocket } from '@vuecraft/core'
const { status, data, send, on, connect, disconnect } = useSocket('wss://example.com/ws')
// subscribe to messages of a specific type
on(2, (msg) => {
console.log('unread count:', msg.body.count)
})More Example
Manual Connect
By default, the connection will be opened immediately after mounted. You can manually connect by setting autoConnect to false and then call connect to trigger the connection.
import { useSocket } from '@vuecraft/core'
import { onMounted } from 'vue'
const { status, connect } = useSocket('wss://example.com/ws', {
autoConnect: false,
})
onMounted(() => {
connect()
})Dynamic URL
The url parameter accepts a string, a ref, or a getter function, so you can build the URL dynamically (e.g. with query params).
import { useSocket } from '@vuecraft/core'
import { ref } from 'vue'
const token = ref('abc')
const { send } = useSocket(() => `wss://example.com/ws?token=${token.value}`)Reconnect
Enable automatic reconnection with custom retry configuration.
import { useSocket } from '@vuecraft/core'
const { status } = useSocket('wss://example.com/ws', {
reconnect: {
maxRetries: 5,
retryInterval: 1000,
exponentialBackoff: true,
},
})Heartbeat
Enable heartbeat to keep the connection alive and detect stale connections.
import { useSocket } from '@vuecraft/core'
const { send } = useSocket('wss://example.com/ws', {
heartbeat: {
interval: 3000,
timeout: 5000,
pingMessage: { type: 0, msg: 'ping' },
pongMessage: { type: 0, msg: 'pong' },
},
})Subscribe by Message Type
Use on / off to subscribe to messages whose body.type matches a specific value. This is useful when the server pushes different types of messages over a single connection.
import { useSocket } from '@vuecraft/core'
const { on, off } = useSocket('wss://example.com/ws')
function handleUnread(msg) {
console.log('unread count:', msg.body.count)
}
on(2, handleUnread)
// unsubscribe later
off(2, handleUnread)Callbacks
You can pass callback functions to the options to be called when the connection opens, closes, errors, or receives a message.
import { useSocket } from '@vuecraft/core'
const { data, error, status } = useSocket('wss://example.com/ws', {
onOpen: () => {
console.log('connected')
},
onClose: () => {
console.log('disconnected')
},
onError: (err) => {
console.log(err)
},
onMessage: (msg) => {
console.log('message:', msg)
},
})Send Message
Send a message to the server. The message will be JSON-serialized if it is an object.
import { useSocket } from '@vuecraft/core'
const { send } = useSocket('wss://example.com/ws')
// object will be JSON-serialized
send({ type: 1, body: { msg: 'hello' } })
// string is sent as-is
send('raw text')Manual Disconnect
You can disconnect manually by calling the disconnect function. The connection will also be disconnected automatically on unmount.
import { useSocket } from '@vuecraft/core'
const { disconnect } = useSocket('wss://example.com/ws')
disconnect()Declaration Types
SocketStatus
enum SocketStatus {
CONNECTING = 0,
OPEN = 1,
CLOSING = 2,
CLOSED = 3,
}SocketOptions
interface SocketOptions {
// whether to connect automatically on mount (default: true)
autoConnect?: boolean
// WebSocket sub-protocols
protocols?: string | string[]
// reconnect configuration
reconnect?: SocketReconnectOptions
// heartbeat configuration
heartbeat?: SocketHeartbeatOptions
// called when the connection opens
onOpen?: () => void
// called when the connection closes
onClose?: () => void
// called when an error occurs
onError?: (error: any) => void
// called when a message is received
onMessage?: (data: any) => void
}SocketReconnectOptions
interface SocketReconnectOptions {
// max retry count (default: 3)
maxRetries?: number
// retry interval in ms (default: 3000)
retryInterval?: number
// whether to use exponential backoff (default: true)
exponentialBackoff?: boolean
}SocketHeartbeatOptions
interface SocketHeartbeatOptions {
// heartbeat interval in ms (default: 30000)
interval?: number
// heartbeat timeout in ms (default: 5000)
timeout?: number
// ping message content
pingMessage?: string | Record<string, any>
// pong message content (used to match heartbeat response)
pongMessage?: Record<string, any>
}SocketReturn
interface SocketReturn {
// underlying WebSocket client instance
client: Ref<WebSocketClient | null>
// current connection status
status: Ref<SocketStatus>
// latest received message
data: Ref<any>
// latest error
error: Ref<unknown>
// connect to the WebSocket server
connect: () => void
// disconnect from the WebSocket server
disconnect: () => void
// reconnect to the WebSocket server
reconnect: () => void
// send a message to the server
send: (data: string | object) => void
// subscribe to messages of a specific body.type
on: (type: number, callback: EventCallback) => void
// unsubscribe from messages of a specific body.type
off: (type: number, callback: EventCallback) => void
}