可在客户端和服务端双向通信,加入了客户端心跳检测和断开重连机制,代码实现过程已经有比较详细的注释
React Native 客户端代码WebSocketClient.js
import {
DeviceEventEmitter
} from 'react-native';
const url = 'ws://xxx/websocket/chat';
let that = null;
export default class WebSocketClient {
constructor() {
this.ws = null;
that = this;
}
/**
* 获取WebSocket单例
* @returns {WebSocketClient}
*/
static getInstance() {
if (!this.instance) {
this.instance = new WebSocketClient();
}
return this.instance;
}
/**
* 初始化WebSocket
*/
initWebSocket() {
try {
//timer为发送心跳的计时器
this.timer && clearInterval(this.timer);
this.ws = new WebSocket(url);
this.initWsEvent();
}