WebSocket
WebSocket组件,提供长链接功能。
属性
属性名 | 类型 | 说明 |
---|---|---|
onopen | callback: () => void | 链接连上时的回调 |
onmessage | callback: (event: MessageEvent) => void | 接收消息的回调 |
onclose | callback: (event: CloseEvent) => void | 链接关闭时的回调 |
onerror | callback: () => void | 链接出错时的回调 |
方法
js
/**
* 连接WebSocket(构造方法)
*
* @param url 链接地址
*/
WebSocket(url: string);
js
/**
* 关闭WebSocket
*/
close();
js
/**
* 发送消息
*
* @param data 消息
*/
send(data: string);
MessageEvent
属性名 | 类型 | 说明 |
---|---|---|
data | string | 消息文本 |
CloseEvent
属性名 | 类型 | 说明 |
---|---|---|
code | number | 错误码 |
reason | string | 错误原因描述 |
Close码
code | Reason |
---|---|
1000 | CLOSE_NORMAL |
1001 | CLOSE_GOING_AWAY |
1002 | CLOSE_PROTOCOL_ERROR |
1003 | CLOSE_UNSUPPORTED |
1005 | CLOSE_NO_STATUS |
1006 | CLOSE_ABNORMAL |
1007 | UNSUPPORTED_DATA |
1008 | POLICY_VIOLATION |
1009 | CLOSE_TOO_LARGE |
1010 | MISSING_EXTENSION |
1011 | INTERNAL_ERROR |
1012 | SERVICE_RESTART |
1013 | TRY_AGAIN_LATER |
1015 | TLS_HANDSHAKE |
示例
js
// 建立连接
let ws = new WebSocket('ws://x.x.x.x:8000');
// 设置各种监听回调
ws.onopen = () => {
console.log('WebSocket onOpen');
};
ws.onmessage = (event) => {
console.log('WebSocket onMessage, event.data = ' + event.data);
};
ws.onclose = (event) => {
console.log('WebSocket onClose, event.code = ' + event.code + ', event.reason = ' + event.reason);
};
ws.onerror = () => {
console.log('WebSocket onError');
};
// 关闭连接
ws.close();
// 发送消息
ws.send('test message!');