Simple and useful chat room technology--websocket

Source: Internet
Author: User
Tags php class

Today, many Web sites are polled for the technology they use to implement push technology. Polling is at a specific time interval (such as every 1 seconds), the browser sends an HTTP request to the server, and then the server returns the latest data to the client's browser. This traditional pattern brings with it the obvious drawback that the browser needs to constantly make requests to the server, but the header of the HTTP request is very long, and the data contained in it may be a small value, which consumes a lot of bandwidth and server resources.

Ajax polling--"timed through AJAX query server"

and the newer technology to do the polling effect is comet, using Ajax. However, although this technology can achieve two-way communication, but still need to make requests, and in comet, the widespread use of long links, which also consumes a lot of server bandwidth and resources.

comet--new technology arising from the rise of Ajax technology

Uncover the mystery of Ajax long polling with plain English

In the face of this situation, HTML5 defines the WebSocket protocol, which can better save the server resources and bandwidth and achieve real-time communication.

International practice, first on Wikipedia's interpretation.

"WebSocket is a protocol that HTML5 begins to provide full-duplex communication on a single TCP connection. "

--Wikipedia

The above is Wikipedia's explanation of websocket, do not ask me how to explain the above paragraph, because I did not understand, then I would like to explain the following words (only my understanding):

WebSocket is a protocol that can simply be seen as a supplemental protocol to the HTTP protocol, websocket the HTTP protocol to complete the server actively and the client to transmit data in real time.

This is the relationship between WebSocket and HTTP, there are intersections, but not all.

WebSocket just HTML5 one of the APIs (HTML5 introduced a lot of new APIs, likes), this API can implement WebSocket technology through WebSocket protocol.

In the WebSocket API, the browser and server only need to do a handshake, and then a fast channel is formed between the browser and the server. The data can be transmitted to each other directly between the two.

The key point is how to "shake hands", so long as we have done the handshake, then Webscoket technology can be used.

The previous said WebSocket and HTTP have the intersection, or can say WebSocket with the help of HTTP is reflected here, you can see the red dots in the figure, respectively, is the WebSocket request head and the response head, one back, the handshake is completed, Real-time connectivity is also built up!

Here are some important head parameters:

//指定WebSocket协议Sec-WebSocket-Version: 13 //指定Websocket Draft协议版本Sec-WebSocket-Key:Cv8RLRCr07Ujlqexqq9Nrw== //验证key值,由浏览器随机生成,可以理解为一个校验码Reponse:Connection:Upgrade ; Upgrade:webSocket;//没错我就是webSocketSec-WebSocket-Accept:rC+mM80welcslAqBHpav4MSDzAU= ;//这是返回头校验码,和请求头的Key配对Sec-WebSocket-Version: 13 //指定Websocket Draft协议版本

The above is a complete websocket handshake, the handshake can be done in real-time communication.

Let's take a look at the previous code:

The service-side language used in this article is PHP, other languages can be compared to see, the big principle is the same:

WebSocket Demo Download link (the code is too long, download it directly)

How to use

Windows下要用cmd启动server.php文件,Linux同理然后用浏览器访问index.htmlDemo是上网找的,不能当做实际用途,简单看看运行流程就好

The code needs to change the index.html URL and the server.php IP.

I'll explain a few important modules.

server.php:

  <?php include  ' websocket.class.php ';  $config =array ( ' address ' =>< Span class= "hljs-string" > ' 127.0.0.1 ',  ' Port ' => ' 8000 ', Span class= "hljs-string" > ' event ' => ' wsevent ', //the function name of the callback function Span class= "hljs-string" > ' log ' =>true,);  $websocket = new websocket ($ config);  $websocket->run ();           

server.php: Run server.php with CMD, reference and instantiate the Websocket.class.php class library, and execute the Run method, which acts as a "server" that continues to hang the connection and make the corresponding action when the client has a message.

Index.html:

<!doctype html><Html><Head><Metacharset="Utf-8" ><Title>websocket_test</Title><ScriptSrc="Http://libs.baidu.com/jquery/1.9.1/jquery.min.js" ></Script></Head><Body><TextAreaclass="Log"style="width:100%; height:500px; " >=======websocket======</Textarea><InputType="Button"Value=Connectiononclick="Link ()" ><InputType="Button"Value=Disconnectonclick="Dis ()" ><InputType="Text"Id="Text" ><InputType="Button"Value=Sendonclick="Send ()" ><Script>functionLink(){var url=' ws://127.0.0.1:8000 '; socket=New WebSocket (URL); socket.onopen=function() {log (' Connection succeeded ')}socket.onmessage=function(msg) {log (' Get the message: ' +msg.data ';Console.log (msg);} Socket.onclose=function() {log (' Disconnect ')}}functionDis() {socket.close (); socket=null;}functionLog(VAR1) {$('. Log '). Append (var1+"\ r \ n");}function send  () {Socket.send ($ ( ' #text '). attr (function send2  () {var json = json.stringify ({ Span class= "hljs-string" > ' type ':  ' php ',  ' msg ': $ ( ' #text2 '). attr ( ' value ')}) socket.send (JSON);} </script></ body></HTML>    

INDEX.HTML:HTML5 provides the WebSocket API, so the client instantiates this API with the parameter IP: port, connecting the WebSocket connection on the server side.

function Roboot ()

<?functionRoboot($sign,$t) {Global$websocket;Switch ($t) {Case' Hello ':$show =' Hello,git @ OSC ';BreakCase' Name ':$show =' Robot ';BreakCase' Time ':$show =' Current time: '. Date (' y-m-d h:i:s ');BreakCase' Goodbye ':$show =' (^_^)/~~ goodbye ';$websocket->write ($sign,' Robot: '.$show);$websocket->close ( $sign); return; break; case  ' King of the Land Tiger ':  $array = array ( ' chicken stew mushroom ',  ' pagoda quake River Demon ',  ' granules are hard ');  $show =  $array [rand (0,2)]; break; default: $show = (⊙o⊙?) Do not understand, you can try to say: Hello,name,time, Goodbye, the king of the Land Tiger.  $websocket->write ( $sign,  $show);             

function Roboot (): Specifies the client's operation and service-side reply information, the client sends the ' king cover to the Tiger ', the service side return information ' chicken stew mushroom '/' Pagoda Quake River Demon '/' grain is hard '.

The article at the end of a small science:

About sockets and Webscoket

Sockets are not really a protocol. It works at the OSI model Session layer (layer 5th), which is a layer of abstraction that exists to facilitate direct use of the lower level protocol (typically TCP or UDP).

The first set of Socket APIs was Berkeley sockets, implemented in C. It is the de facto standard for sockets, POSIX sockets is built on it, and many programming languages follow this set of APIs, which can be seen in JAVA and Python.

The following excerpt is a more understandable text (from the HTTP and socket long connections and short connection differences):

A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, the socket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.

Host A's application communicates with host B's application and must establish a connection through the socket, and the socket connection must be built with the underlying TCP/IP protocol to establish a TCP connection. Establishing a TCP connection requires the underlying IP protocol to address the hosts in the network. We know that the IP protocol used by the network layer can help us to locate the target host based on the IP address, but there may be multiple applications running on one host, and how to communicate with the specified application is specified by the TCP or UPD address, or the port number. This makes it possible for a Socket instance to uniquely represent a communication link for an application on a host.

WebSocket, however, is a complete application-layer protocol that contains a set of standard APIs.

As a result, WebSocket is easier to use and the Socket is more flexible.

To put it simply, the socket is an application interface, is abstract, websocket and HTTP are concrete implementations,

Reference article:

https://www.zhihu.com/question/20215561 answer: What is WebSocket? 》

Https://zh.wikipedia.org/wiki/WebSocket "Wikipedia: WebSocket"

Http://zengrong.net/post/2199.htm "Zrong ' s Blog"

Original:
1190000005041671

Simple and useful chat room technology--websocket

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.