Cocos Creator WebSocket
实例。
需要注意几个问题:
1、send()
发送的数据格式,这里是有要求的。
2、接收到的数据需要进行一个反序列化。
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
| let ws = new WebSocket("ws://192.168.79.2:7070"); ws.onopen = () => { console.log("连接成功"); ws.send("{\"Version\":{ \"Version\": \"v0.0.1\"}}"); }; ws.onmessage = (event) => { let data = event.data; if (typeof data === "string") { console.log("Received string data:", data); } else if (data instanceof ArrayBuffer) { console.log("Received ArrayBuffer data:", data); const byteArray = new Uint8Array(data); console.log("Byte array:", byteArray); } else if (data instanceof Blob) { console.log("Received Blob data:", data); const reader = new FileReader(); reader.onload = () => { const arrayBuffer = reader.result as ArrayBuffer; console.log("ArrayBuffer:", arrayBuffer); const byteArray = new Uint8Array(arrayBuffer); console.log("Byte array:", byteArray); let jsonString = new TextDecoder().decode(byteArray) console.log("jsonSt = ",jsonString); let data1 = JSON.parse(jsonString); console.log("data1 = ",data1); }; reader.readAsArrayBuffer(data); } else { console.log("Received unknown data type:", data); } }; ws.onclose = (event) => { console.log(`WebSocket closed: ${event.code} ${event.reason}`); };
|