aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/api/websocket/index.html
blob: e2dac93e8c573ac104d248a227c3df1e792e9565 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
---
title: WebSocket
slug: Web/API/WebSocket
translation_of: Web/API/WebSocket
---
<div>{{APIRef("Web Sockets API")}}{{SeeCompatTable}}</div>

<p>Об'єкт <code>WebSocket надає </code>API (інтерфейс) для створення і керування  <a href="/en-US/docs/Web/API/WebSockets_API">WebSocket</a>-з'єднаннями з сервером connection to a server, а також для надсилання і отримання повідомлень з даними.</p>

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

<pre class="syntaxbox">new WebSocket(
  in DOMString url,
  in optional DOMString protocols
);
</pre>

<dl>
 <dt><code>url</code></dt>
 <dd>Це адреса URL, до якої треба підключитись. Тобто адреса, з якої буде відповідати WebSocket на сервері.</dd>
 <dt><code>protocols</code> {{optional_inline}}</dt>
 <dd>Це один протокол або масив протоколів. Протокол - це текст. Ці протоколи потрібні, щоб вказати під-протоколи, щоб один сервер міг виконувати декілька під-протоколів WebSocket (на приклад, вам потрібен сервер, який здатний працювати з різними типами взаємодій залежно від протоколу). Якщо ви не вкажете протокол, то WebSocket буде вважати, що отримав пустий рядок.</dd>
</dl>

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

<dl>
 <dt><code>SECURITY_ERR</code></dt>
 <dd>The port to which the connection is being attempted is being blocked.</dd>
</dl>

<h2 id="Method_overview">Method overview</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <td><code>void <a href="#close()">close</a>(in optional unsigned long code, in optional DOMString reason);</code></td>
  </tr>
  <tr>
   <td><code>void <a href="#send()">send</a>(in DOMString data);</code></td>
  </tr>
 </tbody>
</table>

<h2 id="Attributes">Attributes</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <td class="header">Attribute</td>
   <td class="header">Type</td>
   <td class="header">Description</td>
  </tr>
  <tr>
   <td><code>binaryType</code></td>
   <td>{{DOMXref("DOMString")}}</td>
   <td>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.</td>
  </tr>
  <tr>
   <td><code>bufferedAmount</code></td>
   <td><code>unsigned long</code></td>
   <td>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. <strong>Read only</strong></td>
  </tr>
  <tr>
   <td><code>extensions</code></td>
   <td>{{DOMXref("DOMString")}}</td>
   <td>The extensions selected by the server. This is currently only the empty string or a list of extensions as negotiated by the connection.</td>
  </tr>
  <tr>
   <td><code>onclose</code></td>
   <td>{{domxref("EventListener")}}</td>
   <td>An event listener to be called when the WebSocket connection's <code>readyState</code> changes to <code>CLOSED</code>. The listener receives a <a href="/en-US/docs/Web/API/CloseEvent"><code>CloseEvent</code></a> named "close".</td>
  </tr>
  <tr>
   <td><code>onerror</code></td>
   <td>{{domxref("EventListener")}}</td>
   <td>An event listener to be called when an error occurs. This is a simple event named "error".</td>
  </tr>
  <tr>
   <td><code>onmessage</code></td>
   <td>{{domxref("EventListener")}}</td>
   <td>An event listener to be called when a message is received from the server. The listener receives a <a href="/en-US/docs/Web/API/MessageEvent"><code>MessageEvent</code></a> named "message".</td>
  </tr>
  <tr>
   <td><code>onopen</code></td>
   <td>{{domxref("EventListener")}}</td>
   <td>An event listener to be called when the WebSocket connection's <code>readyState</code> changes to <code>OPEN</code>; this indicates that the connection is ready to send and receive data. The event is a simple one with the name "open".</td>
  </tr>
  <tr>
   <td><code>protocol</code></td>
   <td>{{DOMXref("DOMString")}}</td>
   <td>A string indicating the name of the sub-protocol the server selected; this will be one of the strings specified in the <code>protocols</code> parameter when creating the WebSocket object.</td>
  </tr>
  <tr>
   <td><code>readyState</code></td>
   <td><code>unsigned short</code></td>
   <td>The current state of the connection; this is one of the {{anch("Ready state constants")}}. <strong>Read only.</strong></td>
  </tr>
  <tr>
   <td><code>url</code></td>
   <td>{{DOMXref("DOMString")}}</td>
   <td>The URL as resolved by the constructor. This is always an absolute URL. <strong>Read only.</strong></td>
  </tr>
 </tbody>
</table>

<h2 id="Constants">Constants</h2>

<h3 id="Ready_state_constants">Ready state constants</h3>

<p>These constants are used by the <code>readyState</code> attribute to describe the state of the WebSocket connection.</p>

<table class="standard-table">
 <tbody>
  <tr>
   <td class="header">Constant</td>
   <td class="header">Value</td>
   <td class="header">Description</td>
  </tr>
  <tr>
   <td><code>CONNECTING</code></td>
   <td><code>0</code></td>
   <td>The connection is not yet open.</td>
  </tr>
  <tr>
   <td><code>OPEN</code></td>
   <td><code>1</code></td>
   <td>The connection is open and ready to communicate.</td>
  </tr>
  <tr>
   <td><code>CLOSING</code></td>
   <td><code>2</code></td>
   <td>The connection is in the process of closing.</td>
  </tr>
  <tr>
   <td><code>CLOSED</code></td>
   <td><code>3</code></td>
   <td>The connection is closed or couldn't be opened.</td>
  </tr>
 </tbody>
</table>

<h2 id="Methods">Methods</h2>

<h3 id="close()">close()</h3>

<p>Closes the WebSocket connection or connection attempt, if any. If the connection is already <code>CLOSED</code>, this method does nothing.</p>

<pre class="syntaxbox">void close(
  in optional unsigned short code,
  in optional DOMString reason
);
</pre>

<h4 id="Parameters">Parameters</h4>

<dl>
 <dt><code>code</code> {{optional_inline}}</dt>
 <dd>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 <a href="/en-US/docs/Web/API/CloseEvent#Status_codes">list of status codes</a> on the <a href="/en-US/docs/Web/API/CloseEvent"><code>CloseEvent</code></a> page for permitted values.</dd>
 <dt><code>reason</code> {{optional_inline}}</dt>
 <dd>A human-readable string explaining why the connection is closing. This string must be no longer than 123 bytes of UTF-8 text (<strong>not</strong> characters).</dd>
</dl>

<h4 id="Exceptions_thrown">Exceptions thrown</h4>

<dl>
 <dt><code>INVALID_ACCESS_ERR</code></dt>
 <dd>An invalid <code>code</code> was specified.</dd>
 <dt><code>SYNTAX_ERR</code></dt>
 <dd>The <code>reason</code> string is too long or contains unpaired surrogates.</dd>
</dl>

<div class="note">
<p><strong>Note:</strong> In Gecko, this method didn't support any parameters prior to Gecko 8.0 {{geckoRelease("8.0")}}.</p>
</div>

<h3 id="send()">send()</h3>

<p>Transmits data to the server over the WebSocket connection.</p>

<pre class="syntaxbox">void send(
  in DOMString data
);

void send(
  in ArrayBuffer data
);

void send(
  in Blob data
);
</pre>

<h4 id="Parameters_2">Parameters</h4>

<dl>
 <dt><code>data</code></dt>
 <dd>A text string to send to the server.</dd>
</dl>

<h4 id="Exceptions_thrown_2">Exceptions thrown</h4>

<dl>
 <dt><code>INVALID_STATE_ERR</code></dt>
 <dd>The connection is not currently <code>OPEN</code>.</dd>
 <dt><code>SYNTAX_ERR</code></dt>
 <dd>The data is a string that has unpaired surrogates.</dd>
</dl>

<div class="note">
<p><strong>Note:</strong> Gecko's implementation of the <code>send()</code> method differs somewhat from the specification in {{Gecko("6.0")}}; Gecko returns a <code>boolean</code> 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")}}.</p>

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

<h2 id="Example">Example</h2>

<pre class="brush: js">// 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);
});</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th>Specification</th>
   <th>Status</th>
   <th>Comment</th>
  </tr>
  <tr>
   <td>{{SpecName("Websockets", "#the-websocket-interface", "WebSocket")}}</td>
   <td>{{Spec2("Websockets")}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Edge</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("2.0")}}<sup>[1]</sup></td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td>Sub-protocol support</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoDesktop("6.0")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Edge</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("7.0")}}<sup>[1]</sup></td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td>Sub-protocol support</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoMobile("7.0")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

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

<p>The <code>extensions</code> attribute was not supported in Gecko until Gecko 8.0.</p>

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

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications">Writing WebSocket client applications</a></li>
</ul>