WebsockerClient.uts 8.6 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1 2
import { WebSocketManagerListener } from "./WebSocketManager";
import { ConnectSocketOptions, SendSocketMessageOptions, CloseSocketOptions, GeneralCallbackResult } from "../../interface";
DCloud-yyl's avatar
DCloud-yyl 已提交
3
import { ConnectSocketFailImpl, SendSocketMessageFailImpl } from "../../unierror.uts";
DCloud-yyl's avatar
DCloud-yyl 已提交
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
import OkHttpClient from 'okhttp3.OkHttpClient';
import TimeUnit from 'java.util.concurrent.TimeUnit';
import ConnectionPool from 'okhttp3.ConnectionPool';
import Request from 'okhttp3.Request';
import WebSocketListener from 'okhttp3.WebSocketListener';
import WebSocket from 'okhttp3.WebSocket';
import Response from 'okhttp3.Response';
import Okio from 'okio.Okio';
import ByteString from 'okio.ByteString';
import Base64 from 'android.util.Base64';
import JSONObject from 'com.alibaba.fastjson.JSONObject';
import Handler from 'android.os.Handler';
import Looper from 'android.os.Looper';

export class WebsockerClient {
	private listener : WebSocketManagerListener | null = null;
	private options : ConnectSocketOptions | null = null;

	private static connectPool : ConnectionPool | null = null;

	private websocketDelegate : WebsocketDelegate = new WebsocketDelegate();
	constructor(options : ConnectSocketOptions, listener : WebSocketManagerListener) {
		this.options = options;
		this.listener = listener;
	}


	public connect() {
		const kParam = this.options;
		if (kParam != null) {
			const httpClient = this.createHttpClient();

			const request = this.createRequest(kParam);

			if (request == null) {
				return
			}

			// 临时解决方案 , 连接时延迟100ms , 等到js层注册了onOpen后再连接.
			setTimeout(() => {
				httpClient.newWebSocket(request, new SimpleWebsocketListener(this.listener!, this.websocketDelegate, this))
			}, 100);

		}
	}

	public send(options : SendSocketMessageOptions) {
		const success = options.success;
		const fail = options.fail;
		const complete = options.complete;
		if (this.websocketDelegate.websocket == null) {
DCloud-yyl's avatar
DCloud-yyl 已提交
55
			let result = new SendSocketMessageFailImpl(10002);
DCloud-yyl's avatar
DCloud-yyl 已提交
56 57 58 59 60 61
			fail?.(result);
			complete?.(result);
			return
		}

		try {
DCloud-yyl's avatar
DCloud-yyl 已提交
62 63 64 65 66 67 68 69 70
			const sendResult = this.websocketDelegate.websocket?.send(options.data as string);
			if(sendResult != null && !sendResult){
				let result = new SendSocketMessageFailImpl(10001);
				fail?.(result);
				complete?.(result);
				this.listener?.onError(this, "The queue memory exceeds 16 MiB and the connection will be closed");
				return
			}
			
DCloud-yyl's avatar
DCloud-yyl 已提交
71 72 73 74 75 76
			let result : GeneralCallbackResult = {
				errMsg: "sendSocketMessage:ok"
			}
			success?.(result);
			complete?.(result);
		} catch (e : Exception) {
DCloud-yyl's avatar
DCloud-yyl 已提交
77 78 79
			let result = new SendSocketMessageFailImpl(602001);
			const utsError = new UTSError(e.message ?? "")
			result.cause = utsError
DCloud-yyl's avatar
DCloud-yyl 已提交
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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
			fail?.(result);
			complete?.(result);
			this.listener?.onError(this, e.message ?? "");
		}
	}

	public close(options : CloseSocketOptions) {
		const success = options.success;
		const fail = options.fail;
		const complete = options.complete;
		if (this.websocketDelegate.websocket == null) {
			let result : GeneralCallbackResult = {
				errMsg: "closeSocket:fail WebSocket is not connected"
			}
			fail?.(result);
			complete?.(result);
			return
		}
		try {
			var code : Int = 1000;
			if (options.code != null) {
				code = options.code as Int
			}
			this.websocketDelegate.websocket?.close(code, options.reason ?? "");
			let result : GeneralCallbackResult = {
				errMsg: "closeSocket:ok"
			}
			success?.(result);
			complete?.(result);
		} catch (e : Exception) {
			let result : GeneralCallbackResult = {
				errMsg: e.message ?? ""
			}
			fail?.(result);
			complete?.(result);
			this.listener?.onError(this, e.message ?? "");
		}
	}

	private createHttpClient() : OkHttpClient {
		let clientBuilder = OkHttpClient.Builder();
		clientBuilder.readTimeout(24, TimeUnit.HOURS);
		clientBuilder.writeTimeout(24, TimeUnit.HOURS);


		if (WebsockerClient.connectPool == null) {
			WebsockerClient.connectPool = new ConnectionPool();
		}
		clientBuilder.connectionPool(WebsockerClient.connectPool);

		return clientBuilder.build();
	}

	private createRequest(options : ConnectSocketOptions) : Request | null {
		let requestBilder = new Request.Builder();
		try {
			requestBilder.url(options.url);
		} catch (e : Exception) {
			let option = new ConnectSocketFailImpl(600009);
			const listener = options.fail;
			if (listener != null) {
				listener(option);
			}
			return null;
		}


		const protocols = options.protocols;
		if (protocols != null) {
			let protocolsStr = protocols.join(",");
			requestBilder.addHeader("Sec-WebSocket-Protocol", protocolsStr)
		}

		const header = options.header;
		let hasOrigin = false;

		if (header != null) {
			let map = header.toMap();
			if (map != null) {
				for (key in map.keys) {
					if (key.equals("Origin", true)) {
						hasOrigin = true;
					}
					requestBilder.addHeader(key, "" + map[key]);
				}
			}
		}

		if (!hasOrigin) {
			requestBilder.addHeader("Origin", "http://localhost");        // 测试时,有服务器检测Origin导致403,∴加上该句
		}

		return requestBilder.build();
	}


}

class WebsocketDelegate {
	websocket : WebSocket | null = null;
}

class RunnableTask extends Runnable {
DCloud-yyl's avatar
DCloud-yyl 已提交
183
	private callback : (() => void) | null;
DCloud-yyl's avatar
DCloud-yyl 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
	private looper : Looper | null = null;
	constructor(looper : Looper | null, callback : () => void) {
		super();
		this.looper = looper;
		this.callback = callback
	}

	override run() {
		this.callback?.()
	}

	public execute() {
		if (this.looper == null) {
			this.run();
		} else {
			new Handler(this.looper!!).post(this);
		}
	}
}




class SimpleWebsocketListener extends WebSocketListener {
	private listener : WebSocketManagerListener | null = null;
	private websocketDelegate : WebsocketDelegate | null = null;
	private client : WebsockerClient | null = null;
	private looper : Looper | null = null;
	constructor(listener : WebSocketManagerListener, delegate : WebsocketDelegate, client : WebsockerClient) {
		super();
		this.listener = listener;
		this.websocketDelegate = delegate;
		this.client = client;
		this.looper = Looper.myLooper();
	}

	override onOpen(webSocket : WebSocket, response : Response) : void {
		new RunnableTask(this.looper, () => {
			const delegate = this.websocketDelegate;
			if (delegate != null) {
				delegate.websocket = webSocket;
			}
			const client = this.client;
			if (client != null) {
				const wsHeaders = response.headers();
				const headers = new Map<string, string>();
				for (key in wsHeaders.names()) {
					headers.set(key, wsHeaders.values(key).toString())
				}
				this.listener?.onOpen(client, headers);
			}
		}).execute();
	}

	override onMessage(webSocket : WebSocket, bytes : ByteString) : void {
		new RunnableTask(this.looper, () => {
			let sources = bytes.toByteArray();
			let base64Str = Base64.encodeToString(sources, Base64.NO_WRAP);
			let object = new JSONObject();
			object.put("@type", "binary");
			object.put("base64", base64Str);
			const client = this.client;
			if (client != null) {
				this.listener?.onMessage(client, object.toJSONString());
			}
		}).execute();
	}
	override onMessage(webSocket : WebSocket, text : string) : void {
		new RunnableTask(this.looper, () => {
			const client = this.client;
			if (client != null) {
				this.listener?.onMessage(client, text);
			}
		}).execute();
	}
	override onClosing(webSocket : WebSocket, code : Int, reason : string) : void {
		new RunnableTask(this.looper, () => {
			const delegate = this.websocketDelegate;
			if (delegate != null) {
				delegate.websocket = null;
			}
			const client = this.client;
			if (client != null) {
				this.listener?.onClose(client, code, reason);
			}
		}).execute();

	}

	override onClosed(webSocket : WebSocket, code : Int, reason : string) : void {
		new RunnableTask(this.looper, () => {
			const delegate = this.websocketDelegate;
			if (delegate != null) {
				delegate.websocket = null;
			}
			const client = this.client;
			if (client != null) {
				this.listener?.onClose(client, code, reason);
			}
		}).execute();

	}

	override onFailure(webSocket : WebSocket, t : Throwable, response : Response | null) : void {
		new RunnableTask(this.looper, () => {
			const delegate = this.websocketDelegate;
			if (delegate != null) {
				delegate.websocket = null;
			}
			const client = this.client;
			if (client != null) {
				if (t.javaClass.simpleName == "EOFException") {
					this.listener?.onClose(client, 1000, "CLOSE_NORMAL");
				} else {
					this.listener?.onError(client, t.message ?? "");
				}
			}
		}).execute();
	}

}