Home > Web Front-end > H5 Tutorial > Detailed explanation of the use of WebSocket

Detailed explanation of the use of WebSocket

php中世界最好的语言
Release: 2018-03-14 15:17:49
Original
3050 people have browsed it

This time I will bring you a detailed explanation of the use of WebSocket, what are the precautions when using WebSocket, the following is a practical case, let's take a look.

First introduction to WebSocket
1: Understanding websocket
Websocket is a new protocol in HTML. It realizes a real long connection and full-duplex between the browser and the server. Communication (referring to the two-way signal transmission from A to B and B to A on the line at any time of communication).
Most of the protocols we come into contact with now are http protocols. One-way communication is realized through the http protocol in the browser. The browser sends a request and the server responds. Once the request between the client and the server is over, the server cannot take the initiative. Respond to the client and actively return data to the client. For certain requirements, the data must be refreshed in real time to obtain the latest data on the server and displayed to the client. In order to achieve such needs, most companies use polling technology. Polling technology, the browser issues an http request at a specific time interval (such as 1 second), and the server returns the latest data to the browser, achieving real-time refresh of data. Obviously, the pseudo-long connection achieved through this technology , there are some flaws. HTTP requests every once in a while, not every request is meaningful, because the client will not know whether the data on the server has been updated, so there will definitely be invalidity among multiple requests. request (the data returned from the last request is exactly the same as this time).
It can be seen that polling technology has great disadvantages, and websocket realizes a real long connection, and the server can actively send data to the client. It is this feature that can well realize this demand. When data changes on the server, the server can return new data to the client without invalid request responses.
In the process of implementing websocket connection, you need to send a websocket connection request through the browser, and then the server sends a response. This process is usually called "handshaking".

Detailed explanation of the use of WebSocket

2: Java implements websocket
1. The server-side implementation of
JSR356's WebSocket specification uses the javax.websocket.* API. You can use an ordinary Java object (POJO) with the @ServerEndpoint annotation as the endpoint of the WebSocket server. The code example is as follows:
@ServerEndpoint(value= ”/chatServer”)
public class Chat {
Private static Set sessions = Collections.synchronizedSet(new HashSet());
private static List messages = Collections.synchronizedList(new LinkedList());

private HttpSession httpSession;
@OnOpen
public void onOpen(Session session,EndpointConfig config) {
    //to do somthing
}
@OnMessage
public void onMessage(String message, Session session) {
}
@OnClose
public void onClose(Session session, CloseReason reason) {
}
@OnError
public void onError(Throwable t) {
}
}
Copy after login

Code explanation:
The concise code above establishes a WebSocket server @ServerEndpoint(“/chatServer”) annotation The annotation endpoint represents the access endpoint of the WebSocket server running at ws://[Server IP or domain name]:[Server port]/demo/chatServer. The client browser can already initiate HTTP long connections to the WebSocket client API. .
The class annotated with @ServerEndpoint must have a public parameterless Constructor, The @onMessage annotated Java method is used to receive incoming WebSocket information. This information can be in text format or Binary format.
@OnOpen is called when a new connection is established to this endpoint. Parameters provide more details about the other end of the connection. Session indicates the other end of the conversation connection between two WebSocket endpoints and can be understood as a concept similar to HTTPSession.
@OnClose is called when the connection is terminated.
It is very convenient to use annotations to create a websocket server. Although the code is simple, during my practice, I encountered many problems inexplicably. For example, I could not connect to the server no matter what, and the client just reported a 404 error. , not found. But when I checked the server-side code, there seemed to be no problem. Searching for answers online did not find the answer I wanted to solve this problem. Many people must have encountered this problem and were very confused.
However, the server side implemented by websocket does implement some specific requirements very well.
2. Client implementation
The client connects to the server through js code. First, it must create a websocket object on the server side, and then connect to the server.
Code:

/******************************************************/ var msgContainer = document.getElementById(“msgContainer”); // 服务器地址 var wsUrl = “ws://127.0.0.1:8080/demo/chatServer”; // 创建WebSocket对象 var webSocket = new WebSocket(wsUrl); // 与服务器建立连接 webSocket.onopen = function() { 
    console.log(“与服务器连接成功!!”); } // 接收到服务器传来的消息 webSocket.onmessage = function(mes) {
} // 服务器关闭 webSocket.onclose = function() { 
    console.log(“close!”); } // 服务器异常 webSocket.onerror = function() { 
    console.log(“error!”); } // 浏览器刷新或者关闭时,先关闭当前页面的webSocket对象 window.onbeforunload = function() { 
    webSocket.close(); } // 发送消息 function send() { webSocket.send(jsonMsg); } /******************************************************/
Copy after login

代码(var webSocket = new WebSocket(wsUrl);)是在申请一个 WebSocket 对象,参数是需要连接的服务器端的地址,同 HTTP 协议开头一样,WebSocket 协议的 URL 使用 ws://开头,另外安全的 WebSocket 协议使用 wss://开头。
WebSocket 对象一共支持四个消息 onopen, onmessage, onclose 和 onerror,有了这 4 个事件,我们就可以很容易很轻松的驾驭 WebSocket。
当 Browser 和 WebSocketServer 连接成功后,会触发 onopen 消息;如果连接失败,发送、接收数据失败或者处理数据出现错误,browser 会触发 onerror 消息;当 Browser 接收到 WebSocketServer 发送过来的数据时,就会触发 onmessage 消息,参数 mes中包含 Server 传输过来的数据;当 Browser 接收到 WebSocketServer 端发送的关闭连接请求时,就会触发 onclose 消息。我们可以看出所有的操作都是采用异步回调的方式触发,这样不会阻塞 UI,可以获得更快的响应时间,更好的用户体验。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何使用H5的dataset

如何使用css3实现3d立体特效

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template