websocket协议简介

1)什么是websocket

       websocket是HTML5一种新的协议。它实现了浏览器与服务器全双工通信(full-duple)。握手是基于HTTP请求完成。

传统的客户端-服务端请求方式:

基于轮询技术定期对服务器端发出请求,单双工的,每次建立连接请求,直到服务端返回最新数据。HTTP request 的header是非常长的,会浪费很多网络带宽。

        最新的轮询技术基于Ajax的long-polling虽然改进了,可以实现全双工的方式,但是依然需要发出http请求。

改进后的webSocket的请求方式:

websockett API,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

在此WebSocket 协议中,为我们实现即时服务带来了两大好处:

1. Header:互相沟通的Header是很小的-大概只有 2 Bytes

         2. Server Push:服务器的推送,服务器不再被动的接收到浏览器的request之后才返回数据,而是在有新数据时就主动推送给浏览器。     

          

一个是传统的http客户-服务端请求交互图 一个是websocket的客户-服务端请求交互图

2)websocket协议的请求-应答报文格式

Client request (just like in HTTP, each line ends with \r\n and there must be an extra blank line at the end):

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

Server response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
reference:

wikipadia简介:https://en.wikipedia.org/wiki/WebSocket

RFC 6455:https://datatracker.ietf.org/doc/rfc6455/?include_text=1

猜你喜欢

转载自blog.csdn.net/wu5215080/article/details/60462771