11cb0ef41Sopenharmony_ci# Class: WebSocket
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ci> ⚠️ Warning: the WebSocket API is experimental.
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ciExtends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget)
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciThe WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) and [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455).
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ci## `new WebSocket(url[, protocol])`
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ciArguments:
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ci* **url** `URL | string` - The url's protocol *must* be `ws` or `wss`.
141cb0ef41Sopenharmony_ci* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](./Dispatcher.md).
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_ci### Example:
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_ciThis example will not work in browsers or other platforms that don't allow passing an object.
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_ci```mjs
211cb0ef41Sopenharmony_ciimport { WebSocket, ProxyAgent } from 'undici'
221cb0ef41Sopenharmony_ci
231cb0ef41Sopenharmony_ciconst proxyAgent = new ProxyAgent('my.proxy.server')
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ciconst ws = new WebSocket('wss://echo.websocket.events', {
261cb0ef41Sopenharmony_ci  dispatcher: proxyAgent,
271cb0ef41Sopenharmony_ci  protocols: ['echo', 'chat']
281cb0ef41Sopenharmony_ci})
291cb0ef41Sopenharmony_ci```
301cb0ef41Sopenharmony_ci
311cb0ef41Sopenharmony_ciIf you do not need a custom Dispatcher, it's recommended to use the following pattern:
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ci```mjs
341cb0ef41Sopenharmony_ciimport { WebSocket } from 'undici'
351cb0ef41Sopenharmony_ci
361cb0ef41Sopenharmony_ciconst ws = new WebSocket('wss://echo.websocket.events', ['echo', 'chat'])
371cb0ef41Sopenharmony_ci```
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_ci## Read More
401cb0ef41Sopenharmony_ci
411cb0ef41Sopenharmony_ci- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
421cb0ef41Sopenharmony_ci- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455)
431cb0ef41Sopenharmony_ci- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/)
44