南锋

南奔万里空,脱死锋镝余

WebSocket Example in Cocos Creator

Here is a WebSocket example in Cocos Creator.

Important Points to Consider:

  1. The data format sent via send() has specific requirements.
  2. The received data needs to be deserialized.

Code Example:

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
37
38
39
let ws = new WebSocket("ws://192.168.79.2:7070");

ws.onopen = () => {
console.log("Connection successful");
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);
// If you need to convert the ArrayBuffer to a byte array, you can do this:
const byteArray = new Uint8Array(data);
console.log("Byte array:", byteArray);
} else if (data instanceof Blob) {
console.log("Received Blob data:", data);
// If you need to convert the Blob to an ArrayBuffer or byte array, you can use 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}`);
};
+