In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
What is the role of the WebSocket agreement, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
What is WebSocket?
WebSocket is a network communication protocol. RFC6455 defines its communication standard.
WebSocket is a protocol that HTML5 began to provide for full-duplex communication over a single TCP connection.
Why do I need WebSocket?
Anyone who knows the computer network protocol should know that HTTP protocol is a stateless, connectionless, one-way application layer protocol. It uses the request / response model. The communication request can only be initiated by the client, and the server can reply to the request.
This communication model has a drawback: the HTTP protocol does not enable the server to initiate messages to the client.
The characteristic of this one-way request makes it very troublesome for the client to know if the server has continuous state changes. Most Web applications will implement long polling through frequent asynchronous JavaScript and XML (AJAX) requests. Polling is inefficient and a waste of resources (because you have to connect constantly, or HTTP connections are always open).
As a result, engineers have been wondering if there is a better way. That's how WebSocket was invented. WebSocket connections allow full-duplex communication between the client and the server so that either side can push data to the other side through the established connection. WebSocket only needs to establish a connection once to stay connected. This is obviously much more efficient than the continuous establishment of connections in polling mode.
Communication principle and Mechanism of WebSocket
Since it is a browser-based web technology, its communication must be without HTTP,websocket itself, although it is also a new application layer protocol, but it can not exist alone without HTTP.
Specifically, we build a websocket instance on the client and bind it to a server address that needs to be connected to. When the client connects to the server, it will send a HTTP message similar to the following:
As you can see, this is a get request message from HTTP. Notice that there is a upgrade header in the message, which tells the server that the communication protocol needs to be switched to websocket. If the server supports the websocket protocol, it switches its communication protocol to websocket and sends the client a response header similar to the following:
The returned status code is 101, which means that you agree to the client protocol transition request and convert it to websocket protocol. The above processes are accomplished by using HTTP communication, which is called websocket protocol handshake.
After this handshake, the client and the server establish a websocket connection, and the future communication is based on the websocket protocol. So it can be summarized as follows: websocket handshake needs the help of HTTP protocol, and the communication process after establishing the connection uses websocket protocol.
At the same time, we need to understand that the websocket connection is based on the TCP connection we just initiated the HTTP connection. Once the connection is established, we can transfer data. In websocket, there are two types of data transfer: text data and binary data.
Based on the above analysis, we can see that websocket can provide two-way data communication between client and server with low latency and high performance. It subverts the request processing and response mode developed by web, and provides a real client request and server push data mode, which is especially suitable for the development of real-time data interaction applications.
WebSocket client rookie tutorial (runoob.com) WebSocketTest (); function WebSocketTest () {if ("WebSocket" > client API)
The following API is used to create a WebSocket object.
Var Socket = new WebSocket (url, [protocol])
The first parameter in the above code, url, specifies the URL of the connection. The second parameter, protocol, is optional and specifies an acceptable subprotocol.
WebSocket attribute
The following are the properties of the WebSocket object. Suppose we created the Socket object using the above code:
Property description Socket.readyState read-only property readyState represents the connection status, which can be the following value: 0-indicates that the connection has not been established. 1-indicates that the connection is established and can communicate. 2-indicates that the connection is being closed. 3-indicates that the connection is closed or cannot be opened. The Socket.bufferedAmount read-only attribute bufferedAmount has been placed in a queue by send () waiting for transmission, but the number of bytes of UTF-8 text that have not been issued. WebSocket event
The following are events related to the WebSocket object. Suppose we created the Socket object using the above code:
Event handler describes how to trigger the WebSocket method when the openSocket.onopen connection is closed when the messageSocket.onmessage client is triggered to receive server data when the errorSocket.onerror communication is triggered when an error occurs when the closeSocket.onclose connection is closed.
Here are the methods related to the WebSocket object. Suppose we created the Socket object using the above code:
Method description Socket.send () uses the connection to send data Socket.close () to close the connection
WebSocket server
Package com.gaofei.servlet;import javax.servlet.http.HttpServletRequest;import org.apache.catalina.websocket.StreamInbound;import org.apache.catalina.websocket.WebSocketServlet;import com.gaofei.entry.MyMessageInbound;public class DemoServlet extends WebSocketServlet {private static final long serialVersionUID =-4853540828121130946L / * * (non-Javadoc) * create a webSocekt object, and the first parameter represents the protocol The second parameter httqrequest object * @ see org.apache.catalina.websocket.WebSocketServlet#createWebSocketInbound (java.lang.String, javax.servlet.http.HttpServletRequest) * returns a bound message * / @ Override protected StreamInbound createWebSocketInbound (String str,HttpServletRequest req) {System.out.println (req.getRemoteAddr ()) System.out.println (str); return new MyMessageInbound ();}} package com.gaofei.entry;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.CharBuffer;import org.apache.catalina.websocket.MessageInbound;import org.apache.catalina.websocket.WsOutbound;public class MyMessageInbound extends MessageInbound {WsOutbound wsOutbount / / used to send data object @ Override protected void onBinaryMessage (ByteBuffer arg0) throws IOException {/ / receive data trigger to client, binary message file / / TODO Auto-generated method stub} @ Override protected void onTextMessage (CharBuffer message) throws IOException {/ / receive data trigger Text message file System.out.println ("received text message:" + message) Int iTunes 1; Long ms0=System.currentTimeMillis () / 10000; for (; I > 0 +) {Long ms01=System.currentTimeMillis () / 1000; Long ms01_0=ms01-ms0; if (ms01_0 > 10) {wsOutbount.writeTextMessage (CharBuffer.wrap (I +) / / data sent by the client ms0=System.currentTimeMillis () / 1000;} @ Override protected void onClose (int status) {/ / disconnect trigger / / TODO Auto-generated method stub super.onClose (status); System.out.println ("disconnect handshake") } @ Override protected void onOpen (WsOutbound outbound) {/ / connection successfully triggered super.onOpen (outbound); System.out.println ("handshake succeeded"); this.wsOutbount=outbound; try {this.wsOutbount.writeTextMessage (CharBuffer.wrap ("Hello!")) ;} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}}
Pom profile
4.0.0 om.gaof.webSocketServer webSocketServer 0.0.1-SNAPSHOT war org.apache.tomcat tomcat-catalina 7.0.39 provided org.apache.tomcat Tomcat-coyote 7.0.39 provided websocketServer org.apache.tomcat.maven tomcat7-maven-plugin 2.2 8080 /
Web.xml profile
Archetype Created Web ApplicationwsServletcom.gaofei.servlet.DemoServletwsServlet/wsServletWebSocket Agent
If you think of WebSocket communication as a phone connection, Nginx acts like a telephone operator, transferring the call that initiates the phone connection to the designated customer service.
Nginx officially supports WebSocket agents since version 1. 3. If your web application uses the proxy server Nginx, you also need to configure Nginx to enable the WebSocket proxy function.
The following is the reference configuration:
Server {# this section is specific to the WebSockets proxying location / socket.io {proxy_pass http://app_server_wsgiapp/socket.io; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade" Proxy_read_timeout 600;}} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.