Home  >  Article  >  Web Front-end  >  How to use WebSocket

How to use WebSocket

不言
不言Original
2019-01-11 15:37:0814884browse

How to use WebSocket: First create an instance through new WebSocket; then specify the URL of the website that uses WebSocket for communication; and finally handle the WebSocket communication.

How to use WebSocket

The operating environment of this article: Windows 7 system, Dell G3 computer, javascript version 1.8.5.

WebSocket is a technology that allows two-way communication by keeping the server side and client side always connected. This enables real-time communication, such as chat applications and games that multiple people can play at the same time. However, since server-side programs are also required, in this article we will focus on WebSocket in front-end JavaScript.

Let’s first take a look at the basic usage of WebSocket.

In order to use WebSocket with JavaScript, you must first create an instance.

var connection = new WebSocket(【进行通信的URL】);

Create an instance through a new WebSocket.

The URL specified as a parameter is the URL of the website that will use WebSocket for communication in the future.

In other words, code is needed on the server side to handle WebSocket communication.

The URLs we generally see start with "http://" or "https://", but for WebSocket, it is a URL starting from "ws://" or "wss://" /" is used for special communication.

Event handling and methods of WebSocket

In WebSocket, we often use four event handling and two methods.

First, let’s look at the four types of event processing!

var connection = new WebSocket(【进行通信的URL】);
//连接到通信
connection.onopen = function(e) { };
//发生错误时
connection.onerror = function(error) { };
//收到通信
connection.onmessage = function(e) { };
//通信中断
connection.onclose = function() { };

Execute Onopen() when connecting to communication.
Execute onerror() when an error occurs during communication.
Execute onmessage() when receiving data from the server.
Execute OnClose when communication is interrupted ().

Usually, programs that use WebSocket will use the above four events to assemble the program.

In addition, combined with event processing, two methods are commonly used!

//发送数据的方法
connection.send();
 
//切断通信的方法
connection.close();

send(): Send data to the server
close(): Disconnect communication

It mainly uses send() to send data to the server, close() is used to intentionally interrupt Open communication.

The above is the detailed content of How to use WebSocket. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn