cocos creator WebSocket
实例。
需要注意几个问题:
1、send()
发送的数据格式,这里是有要求的。
2、接收到的数据需要进行一个反序列化。
代码语言:javascript复制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}`);
};