We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS


WebWebSockets はユーザのブラウザとサーバ間でインタラクティブな通信セッションを開くことを可能にする技術です。 WebSocket コネクションを使用して、Web アプリケーションは応答の変更をポーリングする代わりに、リアルタイム通信することができます。

注記: We have a working example of the chat/server system used for code snippets that will be made available once our infrastructure is in place for hosting WebSocket examples properly.

Availability of WebSockets

The WebSocket API is available to JavaScript code whose scope is either a DOM Window object or any object implementing WorkerUtils; that is, you can use it from Web Workers.

注記: The WebSockets API (and the underlying protocol) are still in active development, and there are many compatibility issues across browsers at this time (and even among different releases of the same browser).

WebSocket オブジェクトの生成

WebSocket プロトコル使用して、 WebSocketオブジェクトを生成する必要があります。 WebSocket オブジェクトは自動的にサーバとコネクションを開こうとします。

WebSocket コンストラクタは 1 つの必須な引数と、 1 つの省略可能な引数を受け取ります。

WebSocket WebSocket(
  in DOMString url,
  in optional DOMString protocols

WebSocket WebSocket(
  in DOMString url,
  in optional DOMString[] protocols
接続する URL。これは WebSocket サーバが応答する URL にすべきです。
protocols Optional
単一のプロトコル文字列、もしくはプロトコル文字列の配列のどちらか。この文字列はサブプロトコルを特定するために使用できるため、一つのサーバーのみで複数の。Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.


The port to which the connection is being attempted is being blocked.

Connection errors

If an error occurs while attempting to connect, first a simple event with the name "error" is sent to the WebSocket object (thereby invoking its onerror handler), and then the CloseEvent is sent to the WebSocket object (thereby invoking its onclose handler) to indicate the reason for the connection's closing.

As of Firefox 11 however, it is typical to receive a descriptive error message in the console from the Mozilla platform, and a closing code as defined in RFC 6455, Section 7.4 through the CloseEvent.

この新しい WebSocketを作成する例では、 ws://www.example.com/socketserverに接続しています。"protocolOne" というカスタムプロトコルはこの例のリクエストしているソケットの名前で、これは省略可能です。

var exampleSocket = new WebSocket("ws://www.example.com/socketserver", "protocolOne");

returnされた時、 exampleSocket.readyStateCONNECTING 状態となります。その後、connectionがデータを転送する準備が完了すると、 readyStateOPEN 状態になります。

If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:

var exampleSocket = new WebSocket("ws://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);

Once the connection is established (that is, readyState is OPEN), exampleSocket.protocol will tell you which protocol the server selected.

In the above examples ws has replaced http, similarly wss replaces https. Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the HTTP server as ws://www.example.com or wss://www.example.com.


Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's send() method for each message you want to send:

exampleSocket.send("Here's some text that the server is urgently awaiting!"); 

You can send data as a string, Blob, or ArrayBuffer.

注記: Prior to version 11より以前のバージョンのFirefoxは文字列として送信するデータのみサポートされています。

As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an onopen handler to do the work:

exampleSocket.onopen = function (event) {
  exampleSocket.send("Here's some text that the server is urgently awaiting!"); 

Using JSON to transmit objects

One handy thing you can do is use JSON to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data:

// Send text to all users through the server
function sendText() {
  // Construct a msg object containing the data the server needs to process the message from the chat client.
  var msg = {
    type: "message",
    text: document.getElementById("text").value,
    id:   clientID,
    date: Date.now()

  // Send the msg object as a JSON-formatted string.
  // Blank the text input element, ready to receive the next line of text from the user.
  document.getElementById("text").value = "";

Receiving messages from the server

WebSockets is an event-driven API; when messages are received, a "message" event is delivered to the onmessage function. To begin listening for incoming data, you can do something like this:

exampleSocket.onmessage = function (event) {

Receiving and interpreting JSON objects

Let's consider the chat client application first alluded to in Using JSON to transmit objects. There are assorted types of data packets the client might receive, such as:

  • Login handshake
  • Message text
  • User list updates

The code that interprets these incoming messages might look like this:

exampleSocket.onmessage = function(event) {
  var f = document.getElementById("chatbox").contentDocument;
  var text = "";
  var msg = JSON.parse(event.data);
  var time = new Date(msg.date);
  var timeStr = time.toLocaleTimeString();
  switch(msg.type) {
    case "id":
      clientID = msg.id;
    case "username":
      text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>";
    case "message":
      text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>";
    case "rejectusername":
      text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>"
    case "userlist":
      var ul = "";
      for (i=0; i < msg.users.length; i++) {
        ul += msg.users[i] + "<br>";
      document.getElementById("userlistbox").innerHTML = ul;
  if (text.length) {

Here we use JSON.parse() to convert the JSON object back into the original object, then examine and act upon its contents.

Text data format

Text received over a WebSocket connection is in UTF-8 format.

Prior to Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), certain non-characters in otherwise valid UTF-8 text would cause the connection to be terminated. Now Gecko permits these values.

Closing the connection

When you've finished using the WebSocket connection, call the WebSocket method close():


It may be helpful to examine the socket's bufferedAmount attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network.

Security considerations

WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice-versa. In fact, some browsers explicitly forbid this, including Firefox 8 and later.


このページの貢献者: lv7777, hamasaki, ethertank, suzukaze
最終更新者: lv7777,