Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

WebSocket

BaselineWidely available *

Note: This feature is available inWeb Workers.

TheWebSocket object provides the API for creating and managing aWebSocket connection to a server, as well as for sending and receiving data on the connection.

To construct aWebSocket, use theWebSocket() constructor.

Note:TheWebSocket API has no way to applybackpressure, therefore when messages arrive faster than the application can process them, the application will either fill up the device's memory by buffering those messages, become unresponsive due to 100% CPU usage, or both. For an alternative that provides backpressure automatically, seeWebSocketStream.

EventTarget WebSocket

Constructor

WebSocket()

Returns a newly createdWebSocket object.

Instance properties

WebSocket.binaryType

The binary data type used by the connection.

WebSocket.bufferedAmountRead only

The number of bytes of queued data.

WebSocket.extensionsRead only

The extensions selected by the server.

WebSocket.protocolRead only

The sub-protocol selected by the server.

WebSocket.readyStateRead only

The current state of the connection.

WebSocket.urlRead only

The absolute URL of the WebSocket.

Instance methods

WebSocket.close()

Closes the connection.

WebSocket.send()

Enqueues data to be transmitted.

Events

Listen to these events usingaddEventListener() or by assigning an event listener to theoneventname property of this interface.

close

Fired when a connection with aWebSocket is closed.Also available via theonclose property

error

Fired when a connection with aWebSocket has been closed because of an error, such as when some data couldn't be sent.Also available via theonerror property.

message

Fired when data is received through aWebSocket.Also available via theonmessage property.

open

Fired when a connection with aWebSocket is opened.Also available via theonopen property.

Examples

js
// Create WebSocket connection.const socket = new WebSocket("ws://localhost:8080");// Connection openedsocket.addEventListener("open", (event) => {  socket.send("Hello Server!");});// Listen for messagessocket.addEventListener("message", (event) => {  console.log("Message from server ", event.data);});

Specifications

Specification
WebSockets
# the-websocket-interface

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp