var ws = new WebSocket("ws://localhost:8080/msg");
//readyState屬性返回實例對象的當前狀態,共有四種。
//CONNECTING:值為0,表示正在連接。
//OPEN:值為1,表示連接成功,可以通信了。
//CLOSING:值為2,表示連接正在關閉。
//CLOSED:值為3,表示連接已經關閉,或者打開連接失敗
//例如:if (ws.readyState == WebSocket.CONNECTING) { }
//【用於指定連接成功后的回調函數】
ws.onopen = function (evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
};
//ws.addEventListener('open', function (event) {
// ws.send('Hello Server!');
//};
//【用於指定收到服務器數據后的回調函數】
//【服務器數據有可能是文本,也有可能是二進制數據,需要判斷】
ws.onmessage = function (event) {
if (typeof event.data === String) {
console.log("Received data string");
}
if (event.data instanceof ArrayBuffer) {
var buffer = event.data;
console.log("Received arraybuffer");
}
console.log("Received Message: " + evt.data);
ws.close();
};
//[【於指定連接關閉后的回調函數。】
ws.onclose = function (evt) {
console.log("Connection closed.");
};
//發送文本
ws.send("Hello WebSockets!");
//發送Blob數據
var file = document
.querySelector('input[type="file"]')
.files[0];
ws.send(file);
//發送ArrayBuffer
var img = canvas_context.getImageData(0, 0, 400, 320);
var binary = new Uint8Array(img.data.length);
for (var i = 0; i < img.data.length; i++) {
binary[i] = img.data[i];
}
ws.send(binary.buffer);
//webSocket.bufferedAmount
//bufferedAmount屬性,表示還有多少字節的二進制數據沒有發送出去。它可以用來判斷發送是否結束
var data = new ArrayBuffer(10000000);
socket.send(data);
if (socket.bufferedAmount === 0) {
// 發送完畢
} else {
// 發送還沒結束
}
//webSocket.onerror 用於指定報錯時的回調函數
ws.onerror = function (event) {
};
es.addEventListener("error", function (event) {
});
from:https://blog.csdn.net/wangzhanzheng/article/details/78603532
