Implement PHP and websocket chat rooms and swoolewebsocket Based on Swoole

Source: Internet
Author: User

Implement PHP and websocket chat rooms and swoolewebsocket Based on Swoole

Websocket

Websocket is only a network communication protocol

Just like http and ftp, they are all network communication protocols;

Compared with non-persistent protocols such as HTTP, Websocket is a persistent network communication protocol;

Relationship between WebSocket and HTTP

There are intersections, but not all.

Websocket only uses part of the HTTP protocol to complete a handshake. (HTTP three-way handshake, only once)

Http and websocket request headers:


HTTP:

In the past, the client sent a mail request to the server through http (horse riding), the server processed the request (write back), and returned again through http (horse riding); the link was disconnected;

WebSocket:

The client sends a request to the server through http (horse riding),Upgrade:websocketAndConnection:Upgrade(Two tubes). If the server supports the WebSocket protocol (interfaces with two tubes), it will use the Websocket protocol to return available information (discard the horse) and transmit subsequent information, both pipes are used, unless one party manually disconnects the pipe. If the server does not support the pipe, the client request link fails and an error message is returned;

Http and websocket Response Headers:


Differences between websocket and ajax Round Robin and long poll

The first is ajax round-robin. The principle of ajax round-robin is very simple. Let the browser send a request every several seconds and ask whether the server has new information.

Scenario reproduction:

Client: la, whether there is new information (Request)

Server: No (Response)

Client: la, whether there is new information (Request)

Server: No .. (Response)

Client: la, whether there is new information (Request)

Server: You are so annoying. No .. (Response)

Client: La la. Are there any new messages (Request)

Server: Okay. Here you are. (Response)

Client: La la. Are there any new messages (Request)

Server :... No .... No .. No

Long pollPrinciple andAjaxRound Robin is similar, all of which adopt the round robin method, not discussed;

As can be seen from the above, polling is actually constantly establishing an HTTP connection, and then waiting for processing by the server, which can reflect another characteristic of the HTTP protocol,Passive. At the same time, after each http request and response is complete, the server discards all client information. The next request must carry the identity information (cookie ),Stateless;

The emergence of Websocket solves these problems cleanly;

Therefore, the preceding scenario can be modified as follows.

Client: la, I want to establish the Websocket protocol, the required services:Chat and Websocket Protocol Version: 17 (HTTP Request)

Server: OK. Check that the server has been upgraded to the Websocket protocol (HTTP Protocols Switched)

Client: If you have any information, please send it to me ..

Server: OK. I will tell you sometimes.

Client: balab fighting chart alabala

Server: cangjingkong ala

Client: nosebleed. I will wipe it ......

Server: Haha Boolean Education! hahahahaha

Server: laugh at me, haha

Swoole

However, in order to use PHP with HTML5 to complete a WebSocket request and response, brother walked through the mountains and found Swoole in the depths of the dense forest:

The PHP asynchronous, parallel, and high-performance network communication framework, written in pure C language, provides PHP asynchronous multi-thread server, asynchronous TCP/UDP network client, asynchronous MySQL, database connection pool, asyncTask, message queue, millisecond timer, asynchronous file read/write, asynchronous DNS query.

Supported services:

HttpServer

WebSocket Server

TCP Server

TCP Client

Async-IO (asynchronous)

Task (scheduled Task)

Environment dependency:

Only Linux, FreeBSD, MacOS, and other operating systems are supported.

Linux Kernel version 2.3.32 or later

PHP5.3.10 or later

Gcc4.4 or later or clang

Use cmake

Installation:

You must ensure that the system has the following software:

Php-5.3.10 or a later version

Gcc-4.4 or a later version

Make

Autoconf

Swoole runs as a PHP Extension

Installation (root permission ):

Cd swoole

Phpize

./Configure

Make

Sudo make install

Configure php. ini

Extension = swoole. so

Students who want to study Swoole can read the manual by themselves (although not well written, they can still understand it)

Create a chat room

Server: socket. php

// Create a websocket Server Object and listen to port 0.0.0.0: 9502 $ ws = new swoole_websocket_server ("0.0.0.0", 9502 ); // listen to the WebSocket connection opening event $ ws-> on ('open', function ($ ws, $ request) {$ fd [] = $ request-> fd; $ GLOBALS ['fd '] [] = $ fd; // $ ws-> push ($ request-> fd, "hello, welcome \ n ");}); // listen to WebSocket message events $ ws-> on ('message', function ($ ws, $ frame) {$ msg = 'from '. $ frame-> fd. ": {$ frame-> data} \ n"; // var_dump ($ GLOBALS ['fd ']); // exit; foreach ($ GLOBALS ['fd '] as $ aa) {foreach ($ aa as $ I) {$ ws-> push ($ I, $ msg );}} // $ ws-> push ($ frame-> fd, "server: {$ frame-> data }"); // $ ws-> push ($ frame-> fd, "server: {$ frame-> data }");}); // listen to the WebSocket connection close event $ ws-> on ('close', function ($ ws, $ fd) {echo "client-{$ fd} is closed \ n" ;}); $ ws-> start ();

Client: Socket.html

<! DOCTYPE html> 

The above is all about implementing PHP and websocket chat rooms based on Swoole. I believe this article is very helpful for everyone to learn about PHP and websocket and develop chat rooms.

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.