Cocos Creator WebSocket实例:连接、发送与接收数据的实现 | 南锋

南锋

南奔万里空,脱死锋镝余

Cocos Creator WebSocket实例:连接、发送与接收数据的实现

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);
// 如果你需要将 ArrayBuffer 转换为字节数组,可以这样做:
const byteArray = new Uint8Array(data);
console.log("Byte array:", byteArray);
} else if (data instanceof Blob) {
console.log("Received Blob data:", data);
// 如果你需要将 Blob 转换为 ArrayBuffer 或字节数组,可以使用 FileReader
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}`);
};
+