--- title: WebSocket slug: Web/API/WebSocket translation_of: Web/API/WebSocket ---
{{APIRef("Web Sockets API")}}{{SeeCompatTable}}

Об'єкт WebSocket надає API (інтерфейс) для створення і керування  WebSocket-з'єднаннями з сервером connection to a server, а також для надсилання і отримання повідомлень з даними.

Конструктор WebSocket приймає один обов'язковий і один опціональний параметр:

new WebSocket(
  in DOMString url,
  in optional DOMString protocols
);
url
Це адреса URL, до якої треба підключитись. Тобто адреса, з якої буде відповідати WebSocket на сервері.
protocols {{optional_inline}}
Це один протокол або масив протоколів. Протокол - це текст. Ці протоколи потрібні, щоб вказати під-протоколи, щоб один сервер міг виконувати декілька під-протоколів WebSocket (на приклад, вам потрібен сервер, який здатний працювати з різними типами взаємодій залежно від протоколу). Якщо ви не вкажете протокол, то WebSocket буде вважати, що отримав пустий рядок.

Конструктор може повертати помилки. На прикладі нижче помилка про "порт, до якого була спроба підключитися, був заблокований":

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

Method overview

void close(in optional unsigned long code, in optional DOMString reason);
void send(in DOMString data);

Attributes

Attribute Type Description
binaryType {{DOMXref("DOMString")}} A string indicating the type of binary data being transmitted by the connection. This should be either "blob" if DOM {{domxref("Blob")}} objects are being used or "arraybuffer" if {{jsxref("ArrayBuffer")}} objects are being used.
bufferedAmount unsigned long The number of bytes of data that have been queued using calls to {{manch("send")}} but not yet transmitted to the network. This value resets to zero once all queued data has been sent. This value does not reset to zero when the connection is closed; if you keep calling {{manch("send")}}, this will continue to climb. Read only
extensions {{DOMXref("DOMString")}} The extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.
onclose {{domxref("EventListener")}} An event listener to be called when the WebSocket connection's readyState changes to CLOSED. The listener receives a CloseEvent named "close".
onerror {{domxref("EventListener")}} An event listener to be called when an error occurs. This is a simple event named "error".
onmessage {{domxref("EventListener")}} An event listener to be called when a message is received from the server. The listener receives a MessageEvent named "message".
onopen {{domxref("EventListener")}} An event listener to be called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data. The event is a simple one with the name "open".
protocol {{DOMXref("DOMString")}} A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the protocols parameter when creating the WebSocket object.
readyState unsigned short The current state of the connection; this is one of the {{anch("Ready state constants")}}. Read only.
url {{DOMXref("DOMString")}} The URL as resolved by the constructor. This is always an absolute URL. Read only.

Constants

Ready state constants

These constants are used by the readyState attribute to describe the state of the WebSocket connection.

Constant Value Description
CONNECTING 0 The connection is not yet open.
OPEN 1 The connection is open and ready to communicate.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed or couldn't be opened.

Methods

close()

Closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.

void close(
  in optional unsigned short code,
  in optional DOMString reason
);

Parameters

code {{optional_inline}}
A numeric value indicating the status code explaining why the connection is being closed. If this parameter is not specified, a default value of 1000 (indicating a normal "transaction complete" closure) is assumed. See the list of status codes on the CloseEvent page for permitted values.
reason {{optional_inline}}
A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (not characters).

Exceptions thrown

INVALID_ACCESS_ERR
An invalid code was specified.
SYNTAX_ERR
The reason string is too long or contains unpaired surrogates.

Note: In Gecko, this method didn't support any parameters prior to Gecko 8.0 {{geckoRelease("8.0")}}.

send()

Transmits data to the server over the WebSocket connection.

void send(
  in DOMString data
);

void send(
  in ArrayBuffer data
);

void send(
  in Blob data
);

Parameters

data
A text string to send to the server.

Exceptions thrown

INVALID_STATE_ERR
The connection is not currently OPEN.
SYNTAX_ERR
The data is a string that has unpaired surrogates.

Note: Gecko's implementation of the send() method differs somewhat from the specification in {{Gecko("6.0")}}; Gecko returns a boolean indicating whether or not the connection is still open (and, by extension, that the data was successfully queued or transmitted); this is corrected in {{Gecko("8.0")}}.

As of {{Gecko("11.0")}}, support for {{jsxref("ArrayBuffer")}} is implemented but not {{domxref("Blob")}} data types.

Example

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server', event.data);
});

Specifications

Specification Status Comment
{{SpecName("Websockets", "#the-websocket-interface", "WebSocket")}} {{Spec2("Websockets")}} Initial definition

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatGeckoDesktop("2.0")}}[1] {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Sub-protocol support {{CompatUnknown}} {{CompatUnknown}} {{CompatGeckoDesktop("6.0")}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}
Feature Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatUnknown}} {{CompatVersionUnknown}} {{CompatGeckoMobile("7.0")}}[1] {{CompatUnknown}} {{CompatUnknown}} {{CompatVersionUnknown}}
Sub-protocol support {{CompatUnknown}} {{CompatUnknown}} {{CompatGeckoMobile("7.0")}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}

[1] Starting in Gecko 6.0 {{geckoRelease("6.0")}}, the constructor is prefixed; you will need to use MozWebSocket(): var mySocket = new MozWebSocket("http://www.example.com/socketserver");

The extensions attribute was not supported in Gecko until Gecko 8.0.

Prior to Gecko 11.0 {{geckoRelease("11.0")}}, outbound messages sent using the send() method were limited to 16 MB. They can now be up to 2 GB in size.

See also