WebSocket - Web APIs 编辑

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

To construct a WebSocket, use the WebSocket() constructor.

Note:

This feature is available in Web Workers.

Constructor

WebSocket(url[, protocols])
Returns a newly created WebSocket object.

Constants

ConstantValue
WebSocket.CONNECTING0
WebSocket.OPEN1
WebSocket.CLOSING2
WebSocket.CLOSED3

Properties

WebSocket.binaryType
The binary data type used by the connection.
WebSocket.bufferedAmount Read only
The number of bytes of queued data.
WebSocket.extensions Read only
The extensions selected by the server.
WebSocket.onclose
An event listener to be called when the connection is closed.
WebSocket.onerror
An event listener to be called when an error occurs.
WebSocket.onmessage
An event listener to be called when a message is received from the server.
WebSocket.onopen
An event listener to be called when the connection is opened.
WebSocket.protocol Read only
The sub-protocol selected by the server.
WebSocket.readyState Read only
The current state of the connection.
WebSocket.url Read only
The absolute URL of the WebSocket.

Methods

WebSocket.close([code[, reason]])
Closes the connection.
WebSocket.send(data)
Enqueues data to be transmitted.

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

close
Fired when a connection with a WebSocket is closed.
Also available via the onclose property
error
Fired when a connection with a WebSocket has been closed because of an error, such as when some data couldn't be sent.
Also available via the onerror property.
message
Fired when data is received through a WebSocket.
Also available via the onmessage property.
open
Fired when a connection with a WebSocket is opened.
Also available via the onopen property.

Examples

// 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

SpecificationStatus
HTML Living Standard
The definition of 'WebSocket' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:131 次

字数:6390

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文