WebSocketsWebSockets入门


备注

本节概述了websocket是什么,以及开发人员为什么要使用它。

它还应该提到websocket中的任何大型主题,并链接到相关主题。由于websocket的文档是新的,您可能需要创建这些相关主题的初始版本。

安装或设置

有关设置或安装Web套接字的详细说明。

web-socket客户端示例

这是javascript中的Web套接字客户端的示例。
它:

  1. 连接到现场演示服务器。
  2. 发送消息。
  3. 收到消息。
  4. 间隔后断开连接。
var mySocket    = null;
var serverUrl   = 'wss://echo.websocket.org';  //  wss: is ws: but using SSL.
var oWebSocket  = window.WebSocket || window.MozWebSocket;
if (oWebSocket) {
    mySocket = new oWebSocket (serverUrl);
    if (mySocket) {
        console.log (mySocket);
        mySocket.onopen     = onSocketOpen;
        mySocket.onclose    = onSocketClose;
        mySocket.onmessage  = onSocketMessage;
        mySocket.onerror    = onSocketError;

        setTimeout (closeSocket, 5000);  //  Be polite and free socket when done.
    }
}

function onSocketOpen (evt) {
    console.log ("Socket is now open.");
    mySocket.send ("Hello from my first live web socket!");
}

function onSocketClose (evt) {
    console.log ("Socket is now closed.");
}

function onSocketMessage (evt) {
    console.log ("Recieved from socket: ", evt.data);
}

function onSocketError (evt) {
    console.log ("Error with/from socket!:");
    console.log (evt);
}

function closeSocket () {
    if (mySocket.readyState !== mySocket.CLOSED) {
        console.log ("Closing socket from our end (timer).");
        mySocket.close ();
    }
    else
        console.log ("Socket was already closed (timer).");
}
 

如果您在控制台中运行该代码,则会得到如下结果:

WebSocket { url: "wss://echo.websocket.org/", readyState: 0, bufferedAmount: 0, onopen: null,
    onerror: null, onclose: null, extensions: "", protocol: "", onmessage: null,
    binaryType: "blob" 
}
2  //  <--- 2 was the socket ID in this instance.
Socket is now open. 
Recieved from socket:  Hello from my first live web socket! 
Closing socket from our end (timer). 
Socket is now closed.