WebSocket

Introducing

websocket 的最大特点就是, 服务器可以主动向客户端推送消息, 客户端也可以主动向服务器发送消息

While a WebSocket connection is functionally somewhat similar to standard Unix-style sockets, they are not related.

尽管 WebSocket 连接 在功能上和 标准的 Unix 风格的socket 类似, 但是这两者之间并没有关联

为什么需要websocket

HTTP 协议有一个缺陷, 通信只能有客户端发起

js客户端websocket

构造函数创建websocket实例

1
const exampleSocket = new WebSocket("wss://www.example.com/socketserver");

websocket.readyState

  • 0: CONNECTING
  • 1: OPEN
  • 2: CLOSING
  • 3: CLOSED

指定回调函数

oncode, onmessage, readState 等是 属性()

send(), close() 是方法

onopen

1
2
3
ws.onopen = () => {
    ws.send('Hello Server');
}

如果要指定多个回调函数, 可以使用addEventListener方法

1
2
3
ws.addEventListener('open', (event) => {
    ws.send('Hello again');
})

onmessage

用于指定 收到服务器数据之后的回调函数, 服务器数据可能是文本, 看也可能是二进制数据(blob对象或者Arraybuffer对象)

1
2
3
4
5
6
7
8
ws.onmessage = function(event){
    if(typeOf event.data === String) {
        console.log("Received data string")
    }
    if(event.data instanceof ArrayBuffer){
        console.log("Received arraybuffer")
    }
}

Send data to server

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
exampleSocket.send("Here's some text that the server is urgently awaiting!");
// You can send data as a string, Blob, or ArrayBuffer.

const msg = {
    type: "message",
    text: document.getElementById("text").value,
    id: clientID,
    date: Date.now(),
};
exampleSocket.send(JSON.stringify(msg));

Receiving messages from server

WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. To handle it,

  1. add an event listener for the message event
  2. use the onmessage event handler
1
2
3
exampleSocket.onmessage = (event) => {
    console.log(event.data);
};

Writing WebSocket client applications - Web APIs | MDN