WebSocket

9.3. Web sockets

9.3.1. 序論

~INFORMATIVE

この仕様は、~Web~appが~server側~processとの双方向~通信を可能化するための, `WebSocket$I ~interfaceを導入する。 ◎ To enable Web applications to maintain bidirectional communications with server-side processes, this specification introduces the WebSocket interface.

注記: この~interfaceは、下層の~networkへの生の~accessを許容するものではない。 例えば,独自~serverを介した~messageの代理送信を用いない限り、この~interfaceを IRC ~clientの実装に利用することはできない。 ◎ This interface does not allow for raw access to the underlying network. For example, this interface could not be used to implement an IRC client without proxying messages through a custom server.

【この訳に固有の表記規約】

この訳の,~algoや定義の記述に利用されている各種記号( ~LET, ~IF, ~THROW 等々)の意味や定義の詳細は,~SYMBOL_DEF_REFを~~参照されたし。

以下の用語は、 ~WebSocket~protocol仕様 `WSP$r にて定義される(この訳では、日本語訳への直接リンクを “参照” として与える):

  • `~status~code@ws(参照)( HTTP 応答~status~codeではないことに注意)
  • ~WebSocket接続は`確立され@wsた(参照
  • `~WebSocket~messageを送信する@ws(参照
  • `~WebSocket~messageを受信した@ws(参照
  • `~WebSocket接続を失敗させる@ws(参照
  • `~WebSocket接続を~closeする@ws(参照
  • `~WebSocket~closing~handshakeを開始する@ws(参照
  • `~WebSocket~closing~handshakeは開始され@wsた(参照
  • ~WebSocket接続は`~closeされ@wsた(参照
  • `~cleanに~closeされた@ws(参照
  • `~WebSocket接続~close~code@ws(参照
  • `~WebSocket接続~close事由@ws(参照
  • `下位protocol@ws(参照
  • `下位protocol名@ws(参照
  • `利用中の下位protocol@ws(参照
  • `利用中の拡張@ws(参照
  • `Sec-WebSocket-Protocol@h ~header(参照
  • `Close ~frame@ws(参照
  • `Ping ~frame@ws(参照
  • `Pong ~frame@ws(参照
  • `~opcode@ws(参照
  • `~payload~data@ws(参照
  • `~app~data@ws(参照
  • `~text~data@ws(参照
  • `~binary~data@ws(参照
  • `~frame種別@ws(参照

9.3.2. `WebSocket^I ~interface

enum `BinaryType@I { `blob$l, `arraybuffer$l };
[Constructor(
    USVString %url,
    optional (DOMString or sequence<DOMString>) %protocols = []
), Exposed=(Window,Worker)]

interface `WebSocket@I : `EventTarget$I {
  readonly attribute USVString `url$m;

  // ready state
  const unsigned short `CONNECTING$m = 0;
  const unsigned short `OPEN$m = 1;
  const unsigned short `CLOSING$m = 2;
  const unsigned short `CLOSED$m = 3;
  readonly attribute unsigned short `readyState$m;
  readonly attribute unsigned long long `bufferedAmount$m;

  // networking
           attribute `EventHandler$I `onopen$m;
           attribute `EventHandler$I `onerror$m;
           attribute `EventHandler$I `onclose$m;
  readonly attribute DOMString `extensions$m;
  readonly attribute DOMString `protocol$m;
  void `close$m(optional [Clamp] unsigned short %code, optional `USVString$I %reason);

  // messaging
           attribute `EventHandler$I `onmessage$m;
           attribute `BinaryType$I `binaryType$m;
  void `send$m(`USVString$I %data);
  void `send$m(`Blob$I %data);
  void `send$m(`ArrayBuffer$I %data);
  void `send$m(`ArrayBufferView$I %data);
};

各 `WebSocket$I ~objには、 `~url@ (`~URL~record$)が結付けられる ◎ Each WebSocket object has an associated url (a URL record).

%socket = new `WebSocket(url [, protocols ] )$m
新たな `WebSocket$I ~objを作成した上で、結付けらた~WebSocket接続を即時に確立する。 ◎ Creates a new WebSocket object, immediately establishing the associated WebSocket connection.
%url は文字列をとり、それが与える`~URL~record$に向けて,接続が確立される。 許容される~schemeは `ws^l, `wss^l いずれかに限られ、他に対しては `SyntaxError$E が投出される。 ~URLに`素片$urlが伴われる場合もそれが投出される。 ◎ url is a string giving the URL over which the connection is established. Only "ws" or "wss" schemes are allowed; others will cause a "SyntaxError" DOMException. URLs with fragments will also cause such an exception.
%protocols (省略可)は、文字列, または 文字列の配列をとり、[ 省略-時は空の配列 / 文字列ならば,その文字列のみからなる配列 ]に等価になる。 配列~内の各 文字列は`下位protocol名$wsを表す。 接続が`確立され$wsるのは、~serverが,これらの`下位protocol$wsの一つを応答に選択して返したときに限られることになる。 どの下位protocol名も、~WebSocket~protocol仕様による定義に従って, `Sec-WebSocket-Protocol$h ~header値を構成する一連の~protocol要素に課される要件に合致する必要がある。 ◎ protocols is either a string or an array of strings. If it is a string, it is equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the empty array. Each string in the array is a subprotocol name. The connection will only be established if the server reports that it has selected one of these subprotocols. The subprotocol names have to match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by the WebSocket protocol specification. [WSP]
%socket . `send( data )$m
~WebSocket接続を用いて %data を伝送する。 %data は[ 文字列, `Blob$I, `ArrayBuffer$I, `ArrayBufferView$I ]のいずれかをとり得る。 ◎ Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
%socket . `close( [ code ] [, reason ] )$m
~WebSocket接続を~closeする。 %code は`~WebSocket接続~close~code$wsとして, %reason は`~WebSocket接続~close事由$wsとして利用される(いずれも省略可)。 ◎ Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
%socket . `url$m
~WebSocket接続を確立するときに利用された`~url$を返す。 ◎ Returns the URL that was used to establish the WebSocket connection.
%socket . `readyState$m
`WebSocket$I ~objの接続の状態を返す。 とり得る値は後述する。 ◎ Returns the state of the WebSocket object's connection. It can have the values described below.
%socket . `bufferedAmount$m
`send()$m を用いて~queueされたが, まだ ~networkに伝送されていない,`~app~data$ws(~UTF-8~text/~binary~data)を成す~byte数を返す。 ◎ Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.
~WebSocket接続が`~closeされ$wsている場合、この属性の値は, `send()$m ~methodが~callされる度に増えることになる(この数値は、接続が`~closeされ$wsても 0 に再設定されない)。 ◎ If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)
%socket . `extensions$m
~serverにより選択された拡張があれば,それを返す。 ◎ Returns the extensions selected by the server, if any.
%socket . `protocol$m
~serverにより選択された`下位protocol$wsを(もしあれば)返す。 これは、下位protocolの折衝を遂行するために,構築子の(配列~形にされた) 2 個目の引数と併用され得る。 ◎ Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.
%socket . `binaryType$m [ = %value ]

この `WebSocket$I ~objからの~binary~dataが~scriptにどう公開されるかを指示する文字列を返す: ◎ Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:

`blob$l
~binary~dataは `Blob$I 形で返された。 ◎ Binary data is returned in Blob form.
`arraybuffer$l
~binary~dataは `ArrayBuffer$I 形で返された。 ◎ Binary data is returned in ArrayBuffer form.
設定して,返される~binary~dataがどう公開されるかを変更できる。 既定では `blob$l になる。 ◎ Can be set, to change how binary data is returned. The default is "blob".
`WebSocket(url, protocols)@m

この構築子の被呼出時には、次の手続きを走らせ~MUST: ◎ The WebSocket(url, protocols) constructor, when invoked, must run these steps:

  1. %~url~record ~LET `~URL構文解析する$( %url ) ◎ Let urlRecord be the result of applying the URL parser to url.
  2. ~IF[ %~url~record ~EQ `失敗^i ] ⇒ ~THROW `SyntaxError$E ◎ If urlRecord is failure, then throw a "SyntaxError" DOMException.
  3. ~IF[ %~url~record の`~scheme$url ~NIN { `ws^l, `wss^l} ] ⇒ ~THROW `SyntaxError$E ◎ If urlRecord's scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
  4. ~IF[ %~url~record の`素片$url ~NEQ ~NULL ] ⇒ ~THROW `SyntaxError$E ◎ If urlRecord's fragment is non-null, then throw a "SyntaxError" DOMException.
  5. ~IF[ %protocols は文字列である ] ⇒ %protocols ~SET その文字列 1 個からなる配列 ◎ If protocols is a string, set protocols to a sequence consisting of just that string.
  6. ~IF[ %protocols 内に重複する値がある ]~OR[ %protocols 内の値に,[ ~WebSocket~protocol仕様の定義による `Sec-WebSocket-Protocol$h ~header値を構成する~protocol要素に課される要件 ]を満たさないものがある ] ⇒ ~THROW `SyntaxError$E ◎ If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by the WebSocket protocol specification, then throw a "SyntaxError" DOMException. [WSP]
  7. この段は`並列的$に走らす ⇒ `~WebSocket接続を確立する$( %~url~record, %protocols, `入口~設定群~obj$ ) `FETCH$r ◎ Run this step in parallel: • Establish a WebSocket connection given urlRecord, protocols, and the entry settings object. [FETCH]

    注記: `~WebSocket接続を確立する$のに失敗した場合 ⇒ それにより,`~WebSocket接続を失敗させる$ws~algoが誘発され ⇒ それにより,`~WebSocket接続を~closeする$ws~algoが呼出され ⇒ それにより,~WebSocket接続は`~closed$wsにされ ⇒ それに伴い,`後述のように$ `close$et ~eventが発火されることになる。 ◎ If the establish a WebSocket connection algorithm fails, it triggers the fail the WebSocket connection algorithm, which then invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below.

  8. ~RET 次のようにされた,新たな `WebSocket$I ~obj ⇒ `~url$ ~SET %~url~record ◎ Return a new WebSocket object whose url is urlRecord.
`url@m
取得子は、次の結果を返さ~MUST ⇒ `~URLを直列化する$( この `WebSocket$I ~objの`~url$ ) ◎ The url attribute's getter must return this WebSocket object's url, serialized.
`readyState@m

この属性は、接続の状態を表し、次の値をとり得る: ◎ The readyState attribute represents the state of the connection. It can have the following values:

`CONNECTING@m (数値 0 )
接続はまだ`確立-済み$wsでない。 ◎ The connection has not yet been established.
`OPEN@m (数値 1 )
~WebSocket接続は`確立-済み$wsで,通信は可能である。 ◎ The WebSocket connection is established and communication is possible.
`CLOSING@m (数値 2 )
接続は~handshakeの~close中にあるか、または `close()$m ~methodが呼出されている。 ◎ The connection is going through the closing handshake, or the close() method has been invoked.
`CLOSED@m (数値 3 )
接続はすでに`~closeされ$wsたか, または~openできなかった。 ◎ The connection has been closed or could not be opened.
此れの作成-時には、この属性は `CONNECTING$m に設定され~MUST。 ◎ When the object is created its readyState must be set to CONNECTING (0).
`extensions@m
この属性は、初期~時には空~文字列を返さ~MUST。 その値は、~WebSocket接続が`確立され$wsた後に, ~protocolからの~feedback節 にて定義されるように,変更され得る。 ◎ The extensions attribute must initially return the empty string. After the WebSocket connection is established, its value might change, as defined below.
`protocol@m
この属性は、初期~時には空~文字列を返さ~MUST。 その値は、~WebSocket接続が`確立され$wsた後に, ~protocolからの~feedback節 にて定義されるように,変更され得る。 ◎ The protocol attribute must initially return the empty string. After the WebSocket connection is established, its value might change, as defined below.
`close(code, reason)@m

被呼出時には、次の手続きを走らせ~MUST: ◎ The close(code, reason) method, when invoked, must run these steps:

  1. ~IF[ %code は与えられている ]~AND[ %code ~NIN { 1000, 3000 ~ 4999 } ] ⇒ ~THROW `InvalidAccessError^E ◎ If code is present, but is neither an integer equal to 1000 nor an integer in the range 3000 to 4999, inclusive, throw an "InvalidAccessError" DOMException.
  2. ~IF[ %reason は与えられている ]: ◎ If reason is present, then run these substeps:

    1. %reason ~SET `~UTF-8符号化する$( %reason ) ◎ Let reasonBytes be the result of encoding reason.
    2. ~IF[ %reason を成す~byte数 ~GT 123 ] ⇒ ~THROW `SyntaxError$E ◎ If reasonBytes is longer than 123 bytes, then throw a "SyntaxError" DOMException.
  3. 以下の項目のうち,最初に該当する段を走らす: ◎ Run the first matching steps from the following list:

    `readyState$m ~IN { `CLOSING$m, `CLOSED$m } の場合: ◎ If the readyState attribute is in the CLOSING (2) or CLOSED (3) state
    何もしない。 ◎ Do nothing.
    注記: 接続は、~closeしつつあるか, すでに~closedである。 ~closedでない場合、最終的には,`後述のように$ `close$et ~eventが発火されることになる。 ◎ The connection is already closing or is already closed. If it has not already, a close event will eventually fire as described below.
    ~WebSocket接続は まだ`確立-済み$wsでない場合: ◎ If the WebSocket connection is not yet established [WSP]
    `~WebSocket接続を失敗させる$ws;
    `readyState$m 属性~値 ~SET `CLOSING$m ◎ Fail the WebSocket connection and set the readyState attribute's value to CLOSING (2). [WSP]
    注記: `~WebSocket接続を失敗させる$ws~algoは ⇒ `~WebSocket接続を~closeする$ws~algoを呼出す ⇒ それにより,~WebSocket接続は~closedになる ⇒ それに伴い,`後述のように$ `close$et ~eventが発火されることになる。 ◎ The fail the WebSocket connection algorithm invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below.
    まだ `~WebSocket~closing~handshakeは開始され$wsていない場合 ◎ If the WebSocket closing handshake has not yet been started [WSP]

    `~WebSocket~closing~handshakeを開始する$ws: ◎ Start the WebSocket closing handshake and set the readyState attribute's value to CLOSING (2). [WSP]

    • %code, %reason いずれの引数も与えられていない場合 ⇒ `Close ~message$wsは,~bodyを持っては~MUST_NOT。 ◎ If neither code nor reason is present, the WebSocket Close message must not have a body.

      注記: ~WebSocket~protocol仕様は、`~WebSocket~closing~handshakeを開始する$ws~algoに~status~codeが要求されるものと,誤って言明している。 ◎ The WebSocket Protocol specification erroneously states that the status code is required for the start the WebSocket closing handshake algorithm.

    • %code 引数が与えられている場合 ⇒ `Close ~message$wsに利用する`~status~code$wsは、その引数に与えられた整数にし~MUST。 ◎ If code is present, then the status code to use in the WebSocket Close message must be the integer given by close. [WSP]
    • %reason 引数も与えられている場合 ⇒ `Close ~message$wsには,`~status~code$wsに加えて %reason も供され~MUST。 ◎ If reason is also present, then reasonBytes must be provided in the Close message after the status code. [WSP]
    `readyState$m 属性~値 ~SET `CLOSING$m ◎ ↑
    注記: `~WebSocket~closing~handshakeを開始する$ws~algoは ⇒ 最終的には`~WebSocket接続を~closeする$ws~algoを呼出すことになる ⇒ それにより、~WebSocket接続は`~closed$wsになる ⇒ それに伴い,`後述のように$ `close$et ~eventが発火されることになる。 ◎ The start the WebSocket closing handshake algorithm eventually invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below.
    他の場合 ◎ Otherwise
    `readyState$m 属性~値 ~SET `CLOSING$m ◎ Set the readyState attribute's value to CLOSING (2).
    注記: `~WebSocket~closing~handshakeは開始され$wsており ⇒ 最終的には`~WebSocket接続を~closeする$ws~algoを呼出すことになる ⇒ それにより~WebSocket接続は`~closed$wsになる ⇒ それに伴い,`後述のように$ `close$et ~eventが発火されることになる。 ◎ The WebSocket closing handshake is started, and will eventually invoke the close the WebSocket connection algorithm, which will establish that the WebSocket connection is closed, and thus the close event will fire, as described below.
注記: `close()$m ~methodは、`~WebSocket~closing~handshakeを開始する$ws以前に送信した~messageを破棄するものではない — 仮に,~UAがそのような~messageをまだ送信-中であったとしても、~handshakeは,その~messageが送信された後にのみ開始されることになる。 ◎ The close() method does not discard previously sent messages before starting the WebSocket closing handshake — even if, in practice, the user agent is still busy sending those messages, the handshake will only start after the messages are sent.
`bufferedAmount@m
この属性は、 `send()$m により~queueされているが,`~event-loop$がその`最初の段$に最後に到達した時点では,~networkにまだ伝送されていない、`~app~data$ws(~UTF-8`~text~data$wsか, または`~binary~data$ws)の~byte数を返さ~MUST。 (したがって これは、現在の~taskの実行-中に伝送された~textを含む — ~UAが~script実行と`並列的$に,背後で~textを転送できるかどうかにかかわらず。) これには、~protocolに起因する~frame法の~overheadや, OS や~network~hardwareによる~bufferingは含まれない。 ◎ The bufferedAmount attribute must return the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but that, as of the last time the event loop reached step 1, had not yet been transmitted to the network. (This thus includes any text sent during the execution of the current task, regardless of whether the user agent is able to transmit text in the background in parallel with script execution.) This does not include framing overhead incurred by the protocol, or buffering done by the operating system or network hardware.

次の簡単な例では、 `bufferedAmount$m 属性を用いて、毎 50ms ごとに一回の頻度で(あるいは~network~~処理が追いつかない場合は追いつける頻度で)更新を送信させる。 ◎ In this simple example, the bufferedAmount attribute is used to ensure that updates are sent either at the rate of one update every 50ms, if the network can handle that rate, or at whatever rate the network can handle, if that is too fast.

var %socket = new WebSocket('ws://game.example.com:12010/updates');
%socket.onopen = function () {
  setInterval(function() {
    if (%socket.bufferedAmount == 0) {
      %socket.send(getUpdateData());
    }
  }, 50);
};

`bufferedAmount$m 属性の利用により、~networkが追いつかない頻度で~dataを送信しなくとも,~networkを使い切れるようになる(その属性の値を常時より注意して監視する必要はあるが)。 ◎ The bufferedAmount attribute can also be used to saturate the network without sending the data at a higher rate than the network can handle, though this requires more careful monitoring of the value of the attribute over time.

`binaryType@m
此れの作成-時には、この属性は,文字列 `blob^l に設定され~MUST。 ◎ When a WebSocket object is created, its binaryType IDL attribute must be set to the string "blob".\
取得子は、最後に設定された値を返さ~MUST。 ◎ On getting, it must return the last value it was set to.\
設定子は、新たな値をこの属性に設定し~MUST。 ◎ On setting, the user agent must set the IDL attribute to the new value.
注記: ~UAは、受信される~binary~dataの扱い方の~hintに,この属性を用いることができる: この属性が `blob^l にされている場合、~dataは~diskへ安全に~spoolするに適するものになる。 `arraybuffer^l にされている場合、より効率的に~memory内に保持するに適するものになる。 もちろん,~UAには、受信された~dataを~memory内に保持するかどうかの決定に,より繊細な経験則を用いることが推奨される: 例えば、~data量,あるいは 直前における, ~scriptによるこの属性に対する変更の頻度を基準にするなど。 この後者の側面は特に重要になる。 何故なら、~UAが~dataを受信した後, かつ それに対する~eventを発火する前に、この属性が変更される可能性も少なからずあるので。 ◎ User agents can use the binaryType attribute as a hint for how to handle incoming binary data: if the attribute is set to "blob", it is safe to spool it to disk, and if it is set to "arraybuffer", it is likely more efficient to keep the data in memory. Naturally, user agents are encouraged to use more subtle heuristics to decide whether to keep incoming data in memory or not, e.g. based on how big the data is or how common it is for a script to change the attribute at the last minute. This latter aspect is important in particular because it is quite possible for the attribute to be changed after the user agent has received the data but before the user agent has fired the event for it.
`send(data)@m

この~methodは、接続を用いて~dataを伝送する。 被呼出時には、次の手続きを走らせ~MUST: ◎ The send(data) method transmits data using the connection.\

  1. ~IF[ `readyState$m 属性 ~EQ `CONNECTING$m ] ⇒ ~THROW `InvalidStateError^E ◎ If the readyState attribute is CONNECTING, it must throw an "InvalidStateError" DOMException. Otherwise, the user agent must run the appropriate set of steps from the following list:
  2. ~IF[ ~WebSocket接続は`確立-済み$wsである ]~AND[ まだ `~WebSocket~closing~handshakeは開始され$wsていない 【すなわち `readyState$m 属性は `OPEN$m 】 ] ⇒ %data 引数の型に応じて,下の表に与えられる[ `~opcode$ws, および`~payload~data$ws ]から構成される`~WebSocket~messageを送信する$ws ⇒ ~bufferを要する所で~bufferが満杯になっているなどの理由で,~dataを送信できない場合 ⇒ この接続の`満杯~flag$を ON にした上で, `~WebSocket接続を~closeする$ws。

    引数の型 `~opcode$ws `~payload~data$ws
    DOMString ~text~frame(数値 1 ) `~UTF-8符号化する$( %data ) の結果。 `UNICODE$r `ENCODING$r
    `Blob$I ~binary~frame(数値 2 ) %data が表現する生~data。 `FILEAPI$r
    `ArrayBuffer$I %data が表現する~bufferに格納されている~data。
    `ArrayBufferView$I %data が参照している,下層の `ArrayBuffer$I ~objが格納する~bufferの中の一区分。

    【 ここの訳は、原文の同じ文言の繰り返しを集約して再構成している。 】

    ◎ If the argument is a string • If the WebSocket connection is established and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of the data argument using a text frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. Any invocation of this method with a string argument that does not throw an exception must increase the bufferedAmount attribute by the number of bytes needed to express the argument as UTF-8. [UNICODE] [ENCODING] [WSP] ◎ If the argument is a Blob object • If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of data using a binary frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. The data to be sent is the raw data represented by the Blob object. Any invocation of this method with a Blob argument that does not throw an exception must increase the bufferedAmount attribute by the size of the Blob object's raw data, in bytes. [WSP] [FILEAPI] ◎ If the argument is an ArrayBuffer object • If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of data using a binary frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. The data to be sent is the data stored in the buffer described by the ArrayBuffer object. Any invocation of this method with an ArrayBuffer argument that does not throw an exception must increase the bufferedAmount attribute by the length of the ArrayBuffer in bytes. [WSP] ◎ If the argument is an object that matches the ArrayBufferView type definition • If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of data using a binary frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. The data to be sent is the data stored in the section of the buffer described by the ArrayBuffer object that data references. Any invocation of this method with this kind of argument that does not throw an exception must increase the bufferedAmount attribute by the length of data's buffer in bytes. [WSP]
  3. `bufferedAmount$m 属性の値 ~INCBY 前~段による`~payload~data$wsに要する~byte数 ◎ ↑

`WebSocket$I ~interfaceを実装する~objは、次の表に与える[ `~event~handler$, および 対応する `~event~handler~event型$ ]を,`~event~handler IDL 属性$として~supportし~MUST : ◎ The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the WebSocket interface:

`~event~handler$ `~event~handler~event型$
`onopen@m `open@et(参照
`onmessage@m `message@et(参照
`onerror@m `error@et(参照
`onclose@m `close@et(参照

9.3.3. ~protocolからの~feedback

~UAは、~WebSocket接続が`確立され$wsたときは,次の手続きを走らす~taskを`~queueし$~MUST: ◎ When the WebSocket connection is established, the user agent must queue a task to run these steps:

  1. %O ~LET 当の `WebSocket$I ~obj ◎ ↓
  2. %O の `readyState$m 属性~値 ~SET `OPEN$m ◎ Change the readyState attribute's value to OPEN (1).
  3. ~IF[ `利用中の拡張$ws ~NEQ ~NULL 値 ] ⇒ %O の `extensions$m 属性~値 ~SET その値 ◎ Change the extensions attribute's value to the extensions in use, if it is not the null value. [WSP]
  4. ~IF[ `利用中の下位protocol$ws ~NEQ ~NULL 値 ] ⇒ %O の `protocol$m 属性~値 ~SET その値 ◎ Change the protocol attribute's value to the subprotocol in use, if it is not the null value. [WSP]
  5. %O に向けて,名前 `open$et の`~eventを発火する$ ◎ Fire an event named open at the WebSocket object.

注記: 上の~algoは、~taskとして`~queueされ$るので、`確立され$wsている~WebSocket接続と, `open$et ~event用に~event~listenerを設定しておく~scriptとの間で競合が生じることはない。 【 すなわち、 `WebSocket()$m を呼出した後に 同期的に登録された~event~listenerが,~serverからの初期~messageを受け取り損ねることはない。】 ◎ Since the algorithm above is queued as a task, there is no race condition between the WebSocket connection being established and the script setting up an event listener for the open event.


~UAは、[ `~frame種別$ws %type の~data %data ]を伴う,`~WebSocket~messageを受信した$wsときは、次の手続きを走らす~taskを`~queueし$~MUST: ◎ When a WebSocket message has been received with type type and data data, the user agent must queue a task to follow these steps: [WSP]

  1. %O ~LET 当の `WebSocket$I ~obj ◎ ↓
  2. ~IF[ %O の `readyState$m 属性~値 ~NEQ `OPEN$m ] ⇒ ~RET ◎ If the readyState attribute's value is not OPEN (1), then return.
  3. %dataForEvent ~LET %type が指示する~dataの種別に応じて,次で与えられる値: ◎ Let dataForEvent be determined by switching on type and binaryType:

    `Text^i
    %data を内容とする,新たな `DOMString^I ◎ type indicates that the data is Text ◎ • a new DOMString containing data
    `Binary^i

    %O の `binaryType$m の値に応じて,次で与えられる値:

    `blob@l
    生~dataが %data を表現する様な,新たな `Blob$I ~obj `FILEAPI$r
    `arraybuffer@l
    %data を内容とする,新たな `ArrayBuffer$I ~obj

    いずれの~objも, %O に`関連する~Realm$内に作成されるとする。

    ◎ type indicates that the data is Binary and binaryType is "blob" ◎ • a new Blob object, created in the relevant Realm of the WebSocket object, that represents data as its raw data [FILEAPI] ◎ type indicates that the data is Binary and binaryType is "arraybuffer" ◎ • a new ArrayBuffer object, created in the relevant Realm of the WebSocket object, whose contents are data
  4. %O に向けて,名前 `message$et の`~eventを発火する$ — `MessageEvent$I を利用し,次のように初期化して ⇒# `origin$m 属性 ~SET `生成元を直列化する$( %O の`~url$の`生成元$url ), `data$m 属性 ~SET %dataForEvent ◎ Fire an event named message at the WebSocket object, using MessageEvent, with the origin attribute initialized to the serialization of the WebSocket object's url's origin, and the data attribute initialized to dataForEvent.

注記: ~UAには、前述の手続きによる~taskを走らす前に,それが効率的に遂行できるかどうか検査しておくことが推奨される。 効率的に遂行できないなら、~bufferを準備している間に,他の`~task~queue$から~taskを取り出す等。 例えば、~dataの到着時には `binaryType$m 属性が `blob^l に設定されていて, ~UAがすべての~dataを~diskへ~spoolしている状況で、その~messageに対し前述の`~task$を走らす直前に,~scriptが `binaryType$m を `arraybuffer^l に切替えた場合、~UAは,~main-threadが停滞しないよう,この`~task$を走らす前に~dataを RAM に戻して, `ArrayBuffer$I ~objを作成する,などが考えられる。 ◎ User agents are encouraged to check if they can perform the above steps efficiently before they run the task, picking tasks from other task queues while they prepare the buffers if not. For example, if the binaryType attribute was set to "blob" when the data arrived, and the user agent spooled all the data to disk, but just before running the above task for this particular message the script switched binaryType to "arraybuffer", the user agent would want to page the data back to RAM before running this task so as to avoid stalling the main thread while it created the ArrayBuffer object.

~text~frameの場合に `message$et ~event用に~handlerを定義する例: ◎ Here is an example of how to define a handler for the message event in the case of text frames:

mysocket.onmessage = function (event) {
  if (event.data == 'on') {
    turnLampOn();
  } else if (event.data == 'off') {
    turnLampOff();
  }
};

ここでの~protocolは、~serverが "on" または "off" ~messageを送信するだけの単純なものとする。 ◎ The protocol here is a trivial one, with the server just sending "on" or "off" messages.


~UAは、`~WebSocket~closing~handshakeが開始され$wsたときは,次を走らす~taskを`~queueし$~MUST: ◎ When the WebSocket closing handshake is started, the user agent must\

  1. 当の `WebSocket$I ~objの `readyState$m 属性~値 ~SET `CLOSING$m ◎ queue a task to change the readyState attribute's value to CLOSING (2).\

( `close()$m ~methodが~callされていた場合、 `readyState$m 属性~値は,この~taskを走らす時点で,すでに `CLOSING$m に設定されていることになる。) ◎ (If the close() method was called, the readyState attribute's value will already be set to CLOSING (2) when this task runs.) [WSP]


~UAは、`~WebSocket接続を~closeする$wsときは(`~cleanに~closeされた$ws場合も含め),次の手続きを走らす~taskを`~queueし$~MUST: ◎ When the WebSocket connection is closed, possibly cleanly, the user agent must queue a task to run the following substeps:

  1. %O ~LET 当の `WebSocket$I ~obj ◎ ↓
  2. %O の `readyState$m 属性~値 ~SET `CLOSED$m ◎ Change the readyState attribute's value to CLOSED (3).
  3. ~IF[ ~UAは`~WebSocket接続を失敗させる$ws必要がある ]~OR[ ~WebSocket接続は その `満杯~flag@ が ON にされた上で`~closeされ$wsた ] ⇒ %O に向けて,名前 `error$et の`~eventを発火する$ ◎ If the user agent was required to fail the WebSocket connection, or if the the WebSocket connection was closed after being flagged as full, fire an event named error at the WebSocket object. [WSP]
  4. %O に向けて,名前 `close$et の`~eventを発火する$ — `CloseEvent$I を利用し,次のように初期化して ⇒# `wasClean$m 属性 ~SET [ 接続は`~cleanに~closeされた$wsならば ~T / ~ELSE_ ~F ], `code$m 属性 ~SET `~WebSocket接続~close~code$ws, `reason$m 属性 ~SET `~BOMはそのままに~UTF-8復号する$( `~WebSocket接続~close事由$ws ) ◎ Fire an event named close at the WebSocket object, using CloseEvent, with the wasClean attribute initialized to true if the connection closed cleanly and false otherwise, the code attribute initialized to the WebSocket connection close code, and the reason attribute initialized to the result of applying UTF-8 decode without BOM to the WebSocket connection close reason. [WSP]

警告: ~UAは、失敗に際し,次の状況を判別し得るような情報を~script側に伝えてはならない。 ◎ User agents must not convey any failure information to scripts in a way that would allow a script to distinguish the following situations:

  • ~serverの~host名を解決できなかった。 ◎ A server whose host name could not be resolved.
  • ~serverへ~packetを成功裡に~routeできなかった。 ◎ A server to which packets could not successfully be routed.
  • 指定された~portへの接続を~serverが拒否した。 ◎ A server that refused the connection on the specified port.
  • ~serverとの TLS ~handshakeを正しく遂行できなかった(例えば,~serverの証明書を検証できなかったなど)。 ◎ A server that failed to correctly perform a TLS handshake (e.g., the server certificate can't be verified).
  • ~serverが~opening~handshakeを完了しなかった(例えば,~serverが~WebSocket~serverではなかったなど)。 ◎ A server that did not complete the opening handshake (e.g. because it was not a WebSocket server).
  • ~WebSocket~serverは正しい~opening~handshakeを送信したが、それが指定する~optionにより,~clientは接続を解除した(例えば~serverは~clientが求めなかった`下位protocol$wsを指定してきたなど)。 ◎ A WebSocket server that sent a correct opening handshake, but that specified options that caused the client to drop the connection (e.g. the server specified a subprotocol that the client did not offer).
  • ~WebSocket~serverは~opening~handshakeを成功裡に完了した後に突如,接続を~closeした。 ◎ A WebSocket server that abruptly closed the connection after successfully completing the opening handshake.

これらすべての場合において, `~WebSocket接続~close~code$wsは、~WebSocket~protocol仕様の要求に従って, 1006 になる。 ◎ In all of these cases, the the WebSocket connection close code would be 1006, as required by the WebSocket Protocol specification. [WSP]

~scriptがこれらの場合を判別できるようになると、攻撃の前準備として,~scriptに利用者の~local~networkの調査を可能にさせ得ることになる。 ◎ Allowing a script to distinguish these cases would allow a script to probe the user's local network in preparation for an attack.

注記: 特に,このことは、~code 1015 が~UAからは利用されないことを意味する(もちろん、~serverが `Close ~frame$wsに誤って利用した場合は除く)。 ◎ In particular, this means the code 1015 is not used by the user agent (unless the server erroneously uses it in its close frame, of course).

この節にて`~queueされ$る どの`~task$も,その`~task源$は `~WebSocket~task源@ とする。 ◎ The task source for all tasks queued in this section is the WebSocket task source.

9.3.4. Ping および Pong ~frame

~WebSocket~protocol仕様は、接続維持, 鼓動, ~network状態探針, 遅延計測, 等々に利用し得る、`Ping ~frame$wsおよび `Pong ~frame$wsを定義する。 これらは現時点では API に公開されていない。 ◎ The WebSocket protocol specification defines Ping and Pong frames that can be used for keep-alive, heart-beats, network status probing, latency instrumentation, and so forth. These are not currently exposed in the API.

~UAは、必要に応じて[ `Ping ~frame$ws / 未請求の`Pong ~frame$ws ]を送信してよい(例えば: ~local~network~NATmappingを保守する, 接続を検出する, 利用者に遅延測定を表示する,などのために)。 ~UAは、これらの~frameを~serverへの援助目的に用いてはならない。 ~serverは必要に応じて適切な時機に~pongするものとされているので。 ◎ User agents may send ping and unsolicited pong frames as desired, for example in an attempt to maintain local network NAT mappings, to detect failed connections, or to display latency metrics to the user. User agents must not use pings or unsolicited pongs to aid the server; it is assumed that servers will solicit pongs whenever appropriate for the server's needs.

9.3.5. `CloseEvent^I ~interface

`WebSocket$I ~objは、その `close$et ~event用に `CloseEvent$I ~interfaceを利用する: ◎ WebSocket objects use the CloseEvent interface for their close events:

[Constructor(DOMString %type, optional `CloseEventInit$I %eventInitDict),
 Exposed=(Window,Worker)]
interface `CloseEvent@I : `Event$I {
  readonly attribute boolean `wasClean$m;
  readonly attribute unsigned short `code$m;
  readonly attribute USVString `reason$m;
};

dictionary `CloseEventInit@I : `EventInit$I {
  boolean wasClean = false;
  unsigned short code = 0;
  USVString reason = "";
};
%event . `wasClean$m
[ 接続は`~cleanに~closeされた$wsなら ~T / ~ELSE_ ~F ]を返す。 ◎ Returns true if the connection closed cleanly; false otherwise.
%event . `code$m
~serverから供された`~WebSocket接続~close~code$wsを返す。 ◎ Returns the WebSocket connection close code provided by the server.
%event . `reason$m
~serverから供された`~WebSocket接続~close事由$wsを返す。 ◎ Returns the WebSocket connection close reason provided by the server.
`wasClean@m
取得子は、初期化-時の値を返さ~MUST。 ◎ The wasClean attribute must return the value it was initialized to.\
この属性は、接続が`~cleanに~closeされた$wsかどうかを表現する。 ◎ It represents whether the connection closed cleanly or not.
`code@m
取得子は、初期化-時の値を返さ~MUST。 ◎ The code attribute must return the value it was initialized to.\
この属性は、~serverから供された `~WebSocket接続~close~code$wsを表現する。 ◎ It represents the WebSocket connection close code provided by the server.
`reason@m
取得子は、初期化-時の値を返さ~MUST。 ◎ The reason attribute must return the value it was initialized to.\
この属性は、~serverから供された`~WebSocket接続~close事由$wsを表現する。 ◎ It represents the WebSocket connection close reason provided by the server.

9.3.6. ~garbage収集

次のいずれかに該当する `WebSocket$I ~objは、~garbage収集されてはならない: ◎ ↓

  • `~event-loop$がその`最初の段$に最後に到達した時点で、 `readyState$m 属性が[ 次の表の 1 列目の値 ]にされていて,[ 同じ行の 2 列目に示される~event型に対し登録されている~event~listenerが在る ]もの。

    `readyState$m `~event~handler~event型$
    `CONNECTING$m (0) `open$et, `message$et, `error$et, `close$et
    `OPEN$m (1) `message$et, `error$et, `close$et
    `CLOSING$m (2) `error$et, `close$et
    ◎ A WebSocket object whose readyState attribute's value was set to CONNECTING (0) as of the last time the event loop reached step 1 must not be garbage collected if there are any event listeners registered for open events, message events, error events, or close events. ◎ A WebSocket object whose readyState attribute's value was set to OPEN (1) as of the last time the event loop reached step 1 must not be garbage collected if there are any event listeners registered for message events, error, or close events. ◎ A WebSocket object whose readyState attribute's value was set to CLOSING (2) as of the last time the event loop reached step 1 must not be garbage collected if there are any event listeners registered for error or close events.
  • その接続は`確立-済み$wsであり,~network伝送-用に~dataが~queueされているもの。 ◎ A WebSocket object with an established connection that has data queued to be transmitted to the network must not be garbage collected. [WSP]

接続が~openしているにもかかわらず, `WebSocket$I ~objが~garbage収集された場合、~UAには,`~WebSocket~closing~handshakeを開始する$wsことが要求される。 このときの `Close ~message$wsは、`~status~code$wsを伴わないものとする。 ◎ If a WebSocket object is garbage collected while its connection is still open, the user agent must start the WebSocket closing handshake, with no status code for the Close message. [WSP]


~UAは, `WebSocket$I ~objを `消滅させる@ 必要が生じたとき(これは `Document$I ~objが消失した時に起こる)は、次を走らせ~MUST: ◎ If a user agent is to make disappear a WebSocket object (this happens when a Document object goes away), the user agent must follow the first appropriate set of steps from the following list:

  1. ~IF[ ~WebSocket接続はまだ`確立-済み$wsでない ] ⇒ `~WebSocket接続を失敗させる$ws ◎ If the WebSocket connection is not yet established [WSP] • Fail the WebSocket connection. [WSP]
  2. ~ELIF[ `~WebSocket~closing~handshakeは開始され$wsていない ] ⇒ `~WebSocket~closing~handshakeを開始する$ws — `Close ~message$wsに用いる`~status~code$wsは 1001 とする ◎ If the WebSocket closing handshake has not yet been started [WSP] • Start the WebSocket closing handshake, with the status code to use in the WebSocket Close message being 1001. [WSP] ◎ Otherwise • Do nothing.