Html 简明教程
HTML - WebSockets
WebSockets 是一种面向 Web 应用程序的下一代双向通信技术,它通过单个套接字进行通信。
WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket.
WebSockets 允许双向通信,这意味着客户端和服务器都可以独立且同时向彼此发送数据。
WebSockets allow bidirectional communication which means both client and server can send data to eachother independently and simultaneously
在与 Web 服务器建立 Web Socket 连接后,我们可以通过调用 send() 方法将数据从浏览器发送到服务器,并通过 onmessage 事件处理程序从服务器接收数据到浏览器。
After establishing a Web Socket connection with the web server, we can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.
Syntax
以下是用于创建新 WebSocket 对象的 API。
Following is the API which creates a new WebSocket object.
var Socket = new WebSocket(url, [protocol] );
这里,第一个参数 url 指明要连接的 URL。第二个属性 protocol 是可选的,如果存在,则指明服务器必须支持的子协议,以便连接成功。
Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.
Attributes of WebSocket
以下是 WebSocket 对象的属性。假设我们如上所述创建了 Socket 对象。
Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above.
Attribute |
Description |
Socket.readyState |
The readonly attribute readyState represents the state of the connection. It can have the following values. A value of 0 indicates that the connection has not yet been established.A value of 1 indicates that the connection is established and communication is possible.A value of 2 indicates that the connection is going through the closing handshake.A value of 3 indicates that the connection has been closed or could not be opened. |
Socket.bufferedAmount |
The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method. |
WebSocket Events
以下是与 WebSocket 对象关联的事件。假设我们如上所述创建了 Socket 对象。
Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above
Event |
Values & Event Handler |
Values & Description |
open |
Socket.onopen |
This event occurs when socket connection is established. |
message |
Socket.onmessage |
This event occurs when client receives data from server. |
error |
Socket.onerror |
This event occurs when there is any error in communication. |
close |
Socket.onclose |
This event occurs when connection is closed. |
WebSocket Methods
以下是与 WebSocket 对象关联的方法。假设我们如上所述创建了 Socket 对象。
Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above −
Method |
Description |
Socket.send() |
The send(data) method transmits data using the connection. |
Socket.close() |
The close() method would be used to terminate any existing connection. |
Setting up HTML client for the server
到目前为止,我们为 WebSocket 设置了一个 Python 服务器。该服务器将在您的终端上运行,因此发送到服务器的任何消息都将在终端上可见。在这里,我们将看到如何设置一个客户端,它可以使用 HTML 和 JavaScript 从服务器接收消息,也可以向服务器发送消息。
So far we setup a python server for websocket. The server will be running on your terminal, so any messages sent to server will be visible at terminal. Here we will see how to setup a client that can receive message from server and also send message to server using HTML and JavaScript.
在文件夹中创建一个 HTML 文件“index.html”
Create a HTML file 'index.html' in the folder
<!DOCTYPE html>
<html lang="en">
<head>
<title>WebSocket Example</title>
</head>
<body>
<h1>WebSocket Client</h1>
<input type="text"
id="messageInput"
placeholder="Type a message..." />
<button id="sendButton">
Send
</button>
<div id="messages">
</div>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open',
() => {
console.log('Connected to server');
});
socket.addEventListener('message',
(event) => {
const messageDiv = document.createElement('div');
messageDiv.textContent = event.data;
document.getElementById('messages').appendChild(messageDiv);
});
document.getElementById('sendButton').addEventListener('click',
() => {
const messageInput = document.getElementById('messageInput');
const message = messageInput.value;
socket.send(message);
messageInput.value = '';
});
</script>
</body>
</html>