WebSocket protocol is a new network protocol based on TCP, which realizes the bidirectional traffic between client and server, and allows the service side to send information to the client actively. WebSocket is an agreement in the HTML5.
HTTP protocol with WebSocket protocol:
The HTTP protocol has only 1.0 and 1.1 two versions,
The HTTP protocol is a stateless response for each request, and when the response is finished, it ends the connection, multiple requests correspond to multiple responses, and each time the connection is re-established.
Added keep-alive in http1.1 (just a recommendation from the client), which can be used to send multiple request and receive multiple response in an HTTP connection. But there is still one response per request.
Connection:keep-alive
This is the notification server after Request/response, do not understand the disconnect TCP connection, the following request/response can still be done through this connection. But this is only a suggestion, the server may not be supported, or it may be a long time, disconnected from the connection. (Popular point on the root server, there may be some things need to find you first don't hang up)
This is not possible to implement the server proactive push message to the client.
So how can it be achieved?
But we can use Ajax polling and long poll technology to create the illusion of a service-side push to the client.
What is Ajax polling?
Ajax polling is a few seconds to let the browser send a request to ask the server when there is a message?
Scene:
Client: Hi, there is no new information (request) Server: No (Response) client: Hi, there is no new information (request) server: No. (Response) Client: Hi, there is no new information (Request) server: no AH. (Response) Client: Hi there is no new message (Request) server: All right, here you are. (Response) Client: Hi, there is no new message (Request) server: No ...
But in practice this will increase the load on the server side and reduce the efficiency of the server.
What is long poll?
Long poll is similar to Ajax polling, but long poll is a blocking pattern. That is, the client sends a request after waiting, know that the server has a message response after the OK
Scene:
Client: Hi, there is no new information (request) Server: No (Response) client: Hi, there is no new information (request) Client: Hi, there is no new information (request)
Long pull reduces the load on the server, but requires a high level of concurrency for the server.
Ajax polling, long poll technology can realize the service-side message real-time notification, but each has shortcomings, are not the fundamental solution.
Since none of them are working, there should be a new agreement.
The WebSocket protocol solves the problem of duplex communication between the client and the server.
Scene:
Client: La LA, I want to set up the WebSocket protocol, required services: Chat,websocket Protocol version: (HTTP Request) server: OK, confirm, upgrade to WebSocket Protocol (HTTP protocols Switched) Client: Please push it to me when you have information. Server: OK, sometimes I will tell you. Service side: Send Stephen Service side: Ah Real Deal master server: hahaha haha ah ha service end: laughing at me hahaha
Request Header
Accept-encoding:gzip, deflate, Braccept-language:zh-cn,zh;q=0.9cache-control:no-cacheConnection:upgrade # Notification Server protocol Upgrade Cookie:jsessionid=450ba8d626f785a1ae3beb9ac9226cd0host:localhost:8099origin:http://localhost : 8099pragma:no-cachesec-websocket-extensions:permessage-deflate; Client_max_window_bitssec-websocket-key: yjbbhsadolewtvna+3y2ow== #传输给服务器的keySec-websocket-version:13 #wesocket版本协议号13Upgrade: WebSocket #协议升级为websocket协议 user-agent:mozilla/5.0 (Windows NT 6.1; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/65.0.3325.181 safari/537.36
Sec-websocket-key This is the client sent to the server, the service side processing and then return to the client client to verify whether to establish a connection.
Connection:upgrade #通知服务器协议升级
Upgrade:websocket #协议升级为websocket协议
This is the core of WebSocket, tell Apache, Nginx and other servers: attention, the initiation is the WebSocket protocol, quickly help me find the corresponding assistant processing ~ not HTTP.
Status code:101 Switching Protocols 101 connection succeeded
Response Header:
#升级成功 Date:thu, APR 2018 03:11:37 GMTsec-websocket-accept:nbf/mym1p/lny0nsmwxyd1wi1ee= #服务端处理之后的key Sec-websocket-extensions:permessage-deflate;client_max_window_bits=15server:apache-coyote/1.1upgrade:websocket
Handshake succeeded!
A simple code example:
JSP client:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Service side:
Package Com.tgb.springactivemq.controller;import Java.io.ioexception;import Java.util.hashset;import Java.util.random;import Java.util.set;import Javax.websocket.onclose;import Javax.websocket.onerror;import Javax.websocket.onmessage;import Javax.websocket.onopen;import Javax.websocket.session;import Javax.websocket.server.serverendpoint;import Org.apache.log4j.Logger; @ServerEndpoint ("/websockettest") public Class Websocketcontroller {private int count = 0; static set<session> Set = new hashset<session> (); Static final Logger Logger = Logger.getlogger (Websocketcontroller.class); Private session session; @OnOpen public void OnOpen (Session sessio) {this.session = Sessio; Set.add (session); this.count++; Logger.info ("Current connection:" + this.count); }//Accept message processing @OnMessage public void OnMessage (String message, Session ss) {Logger.info ("The client message Received is:" + Me Ssage); Random r = new Random (); int tet = r.nextint (1000); try {ss.getbasicremote (). SendText ("The server is sending:" + tet); } catch (IOException e) {e.printstacktrace (); }} @OnError public void OnError (Session s, throwable th) {logger.info (Th.getmessage ()); } @OnClose public void OnClose (Session s) {try {s.close (); Set.remove (s); this.count--; Logger.info ("Current number of connections:" + this.count); Logger.info ("CLOSE WEBSOCKET"); } catch (IOException e) {e.printstacktrace (); } }}
The principle and simple realization of websocket