Home >Common Problem >What is the difference between websocket and socket
Difference: Socket is the API of the TCP/IP network. It is a layer abstracted to facilitate the use of TCP or UDP. It is a set of interfaces between the application layer and the transmission control layer; while WebSocket is A typical application layer protocol.
The operating environment of this tutorial: Windows 7 system, Dell G3 computer.
Related recommendations: "Programming Video"
Introduction and principles of WebSocket
WebSocket protocol is a new protocol for HTML5. It implements full-duplex communication between the browser and the server. The initial handshake needs to be completed with the help of HTTP request.
——Baidu Encyclopedia
Immediate messaging on websites is very common, such as QQ and chat systems on web pages wait. According to previous technical capabilities, polling and Comet technologies are usually used to solve this problem.
The HTTP protocol is a non-persistent, one-way network protocol. After the connection is established, the browser is only allowed to make a request to the server before the server can return the corresponding data. When instant messaging is required, the browser sends a Request request to the server through polling at a specific time interval (such as 1 second), and then returns the latest data to the browser. The most obvious disadvantage of this method is that it needs to continuously send requests, and usually the header of the HTTP request is very long. In order to transmit a small amount of data, a huge price needs to be paid, which is very uneconomical and takes up a lot of bandwidth.
Disadvantages: It will lead to too many unnecessary requests, wasting traffic and server resources. Every request and response wastes a certain amount of traffic on the same header information
However, WebSocket Appearance can compensate for this shortcoming. In WebSocket, the server and browser only need to perform a handshake action through the HTTP protocol, and then establish a separate TCP communication channel for data transmission.
WebSocket is an application layer protocol like HTTP, but it is a two-way communication protocol built on TCP.
Connection process - handshake process
When WebSocket establishes a handshake, data is transmitted through HTTP. But after establishment, the HTTP protocol is not required during actual transmission.
Socket is not actually a protocol, but a layer abstracted for the convenience of using TCP or UDP. It is located at the application layer and A set of interfaces between transport control layers.
Socket is an intermediate software abstraction layer for communication between the application layer and the TCP/IP protocol family. It is a set of interfaces. In the design mode, Socket is actually a facade mode, which hides the complex TCP/IP protocol family behind the Socket interface. For users, a set of simple interfaces is all, allowing Socket to organize data to meet the specified requirements. protocol.
When two hosts communicate, they must connect through Socket, and Socket uses the TCP/IP protocol to establish a TCP connection. TCP connections rely more on the underlying IP protocol, while IP protocol connections rely on lower layers such as the link layer.
WebSocket is a typical application layer protocol.
Socket is a transmission control layer protocol, and WebSocket is an application layer protocol.
WebSocket API is part of the HTML5 standard, but this does not mean that WebSocket must be used in HTML, or can only be used in browser-based used in server applications.
In fact, many languages, frameworks and servers provide WebSocket support, such as:
WebSocket mechanism
The following is a brief introduction to the principle and operating mechanism of WebSocket.
WebSocket is a new protocol in HTML5. It realizes full-duplex communication between the browser and the server, which can better save server resources and bandwidth and achieve real-time communication. It is built on TCP and transmits data through TCP like HTTP. However, its biggest difference from HTTP is:
The interaction between traditional HTTP client and server in non-WebSocket mode is shown in the following figure:
Figure 1. Traditional HTTP request response client-server interaction diagram
The interaction between client and server using WebSocket mode is as shown below:
Figure 2. WebSocket request response client-server interaction diagram
As can be seen from the comparison of the above figure, compared with the traditional HTTP mode where each request-response requires the client to establish a connection with the server, WebSocket is a TCP long-connect communication mode similar to Socket. Once the WebSocket connection is established, subsequent data All are transmitted in the form of frame sequence. Before the client disconnects the WebSocket connection or the server disconnects the connection, there is no need for the client and server to reinitiate the connection request. In the case of massive concurrency and heavy interactive load traffic between the client and the server, it greatly saves the consumption of network bandwidth resources and has obvious performance advantages. Moreover, the client sends and receives messages on the same persistent connection, in real time. The sexual advantage is obvious.
Let’s take a look at the difference between WebSocket communication and traditional HTTP through the interactive messages between the client and the server:
On the client, new WebSocket instantiates a new WebSocket client object. Connect to the server WebSocket URL similar to ws://yourdomain:port/path. The WebSocket client object will automatically parse and identify it as a WebSocket request, thereby connecting to the server port and performing the handshake process between the two parties. The format of the data sent by the client is similar:
List 1. WebSocket client connection message
GET /webfin/websocket/ HTTP/1.1 Host: localhost Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg== Origin: http://localhost :8080 Sec-WebSocket-Version: 13 http://localhost :8080 Sec-WebSocket-Version: 13
It can be seen that the WebSocket connection message initiated by the client is similar to the traditional HTTP message. The "Upgrade: websocket" parameter value indicates that this is the WebSocket type. request, "Sec-WebSocket-Key" is a base64-encoded ciphertext sent by the WebSocket client, and the server must return a corresponding encrypted "Sec-WebSocket-Accept" response, otherwise the client will throw "Error during WebSocket" handshake" error and close the connection.
The data format returned by the server after receiving the message is similar:
List 2.WebSocket server response message
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: K7DJLdLooIwIG/MOpvWFB3y3FE8=
The value of "Sec-WebSocket-Accept" It is calculated by the server using the same key as the client and returned to the client. "HTTP/1.1 101 Switching Protocols" means that the server accepts the client connection of the WebSocket protocol. After such request-response processing, the client server The WebSocket connection handshake is successful, and subsequent TCP communication can be carried out.
In terms of development, the WebSocket API is also very simple. We only need to instantiate WebSocket and create a connection. Then the server and the client can send and respond to each other's messages. In the WebSocket implementation and case analysis section below, you can See detailed WebSocket API and code implementation.
As mentioned above, the implementation of WebSocket is divided into two parts: the client and the server. The client (usually a browser) issues a WebSocket connection request, and the server responds. Implementation An action similar to TCP handshake, thus forming a HTTP long connection fast channel between the browser client and the WebSocket server. Subsequent direct data transmission between the two eliminates the need to initiate a connection and respond.
The following is a brief description of the WebSocket server API and client API.
WebSocket server has basically been supported by various mainstream application server manufacturers that comply with the JEE JSR356 standard specification API. The following lists some common commercial and open source application servers. WebSocket Server support:
Table 1. WebSocket Server support
Manufacturer | Application Server | Remarks |
---|---|---|
IBM | WebSphere | WebSphere 8.0 or above is supported, and versions prior to 7.X combined with MQTT support similar HTTP long connections |
Oracle | WebLogic | WebLogic 12c support, 11g and 10g versions support similar HTTP long connections through HTTP Publish |
Microsoft | #IIS | IIS 7.0 Support |
Apache | Tomcat | Tomcat 7.0.5+ support, 7.0.2X and 7.0.3X support through custom API |
Jetty | Jetty 7.0+ supports |
以下我们使用 Tomcat7.0.5 版本的服务端示例代码说明 WebSocket 服务端的实现:
JSR356 的 WebSocket 规范使用 javax.websocket.*的 API,可以将一个普通 Java 对象(POJO)使用 @ServerEndpoint 注释作为 WebSocket 服务器的端点,代码示例如下:
清单 3.WebSocket 服务端 API 示例
@ServerEndpoint("/echo") public class EchoEndpoint { @OnOpen public void onOpen(Session session) throws IOException { //以下代码省略... } @OnMessage public String onMessage(String message) { //以下代码省略... } @Message(maxMessageSize=6) public void receiveMessage(String s) { //以下代码省略... } @OnError public void onError(Throwable t) { //以下代码省略... } @OnClose public void onClose(Session session, CloseReason reason) { //以下代码省略... } }
代码解释:
上文的简洁代码即建立了一个 WebSocket 的服务端,@ServerEndpoint("/echo") 的 annotation 注释端点表示将 WebSocket 服务端运行在 ws://[Server 端 IP 或域名]:[Server 端口]/websockets/echo 的访问端点,客户端浏览器已经可以对 WebSocket 客户端 API 发起 HTTP 长连接了。
使用 ServerEndpoint 注释的类必须有一个公共的无参数构造函数,@onMessage 注解的 Java 方法用于接收传入的 WebSocket 信息,这个信息可以是文本格式,也可以是二进制格式。
OnOpen 在这个端点一个新的连接建立时被调用。参数提供了连接的另一端的更多细节。Session 表明两个 WebSocket 端点对话连接的另一端,可以理解为类似 HTTPSession 的概念。
OnClose 在连接被终止时调用。参数 closeReason 可封装更多细节,如为什么一个 WebSocket 连接关闭。
更高级的定制如 @Message 注释,MaxMessageSize 属性可以被用来定义消息字节最大限制,在示例程序中,如果超过 6 个字节的信息被接收,就报告错误和连接关闭。
注意:早期不同应用服务器支持的 WebSocket 方式不尽相同,即使同一厂商,不同版本也有细微差别,如 Tomcat 服务器 7.0.5 以上的版本都是标准 JSR356 规范实现,而 7.0.2x/7.0.3X 的版本使用自定义 API (WebSocketServlet 和 StreamInbound, 前者是一个容器,用来初始化 WebSocket 环境;后者是用来具体处理 WebSocket 请求和响应,详见案例分析部分),且 Tomcat7.0.3x 与 7.0.2x 的 createWebSocketInbound 方法的定义不同,增加了一个 HttpServletRequest 参数,使得可以从 request 参数中获取更多 WebSocket 客户端的信息,如下代码所示:
清单 4.Tomcat7.0.3X 版本 WebSocket API
public class EchoServlet extends WebSocketServlet { @Override protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) { //以下代码省略.... return new MessageInbound() { //以下代码省略.... } protected void onBinaryMessage(ByteBuffer buffer) throws IOException { //以下代码省略... } protected void onTextMessage(CharBuffer buffer) throws IOException { getWsOutbound().writeTextMessage(buffer); //以下代码省略... } }; } }
因此选择 WebSocket 的 Server 端重点需要选择其版本,通常情况下,更新的版本对 WebSocket 的支持是标准 JSR 规范 API,但也要考虑开发易用性及老版本程序移植性等方面的问题,如下文所述的客户案例,就是因为客户要求统一应用服务器版本所以使用的 Tomcat 7.0.3X 版本的 WebSocketServlet 实现,而不是 JSR356 的 @ServerEndpoint 注释端点。
对于 WebSocket 客户端,主流的浏览器(包括 PC 和移动终端)现已都支持标准的 HTML5 的 WebSocket API,这意味着客户端的 WebSocket JavaScirpt 脚本具备良好的一致性和跨平台特性,以下列举了常见的浏览器厂商对 WebSocket 的支持情况:
表 2.WebSocket 客户端支持
浏览器 | 支持情况 |
---|---|
Chrome | Chrome version 4+支持 |
Firefox | Firefox version 5+支持 |
IE | IE version 10+支持 |
Safari | IOS 5+支持 |
Android Brower | Android 4.5+支持 |
客户端 WebSocket API 基本上已经在各个主流浏览器厂商中实现了统一,因此使用标准 HTML5 定义的 WebSocket 客户端的 JavaScript API 即可,当然也可以使用业界满足 WebSocket 标准规范的开源框架,如 Socket.io。
以下以一段代码示例说明 WebSocket 的客户端实现:
清单 5.WebSocket 客户端 API 示例
var ws = new WebSocket(“ws://echo.websocket.org”); ws.onopen = function(){ws.send(“Test!”); }; ws.onmessage = function(evt){console.log(evt.data);ws.close();}; ws.onclose = function(evt){console.log(“WebSocketClosed!”);}; ws.onerror = function(evt){console.log(“WebSocketError!”);};
第一行代码是在申请一个 WebSocket 对象,参数是需要连接的服务器端的地址,同 HTTP 协议开头一样,WebSocket 协议的 URL 使用 ws://开头,另外安全的 WebSocket 协议使用 wss://开头。
第二行到第五行为 WebSocket 对象注册消息的处理函数,WebSocket 对象一共支持四个消息 onopen, onmessage, onclose 和 onerror,有了这 4 个事件,我们就可以很容易很轻松的驾驭 WebSocket。
当 Browser 和 WebSocketServer 连接成功后,会触发 onopen 消息;如果连接失败,发送、接收数据失败或者处理数据出现错误,browser 会触发 onerror 消息;当 Browser 接收到 WebSocketServer 发送过来的数据时,就会触发 onmessage 消息,参数 evt 中包含 Server 传输过来的数据;当 Browser 接收到 WebSocketServer 端发送的关闭连接请求时,就会触发 onclose 消息。我们可以看出所有的操作都是采用异步回调的方式触发,这样不会阻塞 UI,可以获得更快的响应时间,更好的用户体验。
想要查阅更多相关文章,请访问PHP中文网!!
The above is the detailed content of What is the difference between websocket and socket. For more information, please follow other related articles on the PHP Chinese website!