Implement PHP and websocket chat room _ php instances based on Swoole

Source: Internet
Author: User
This article uses Swoole to implement PHP + websocket chat rooms. The process is detailed and helpful for the development of chat rooms. if you need it, you can refer to the study. 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. Are there any new messages (Request)

Server: Okay. here you are. (Response)

Client: 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

  
   Title

Script var msg = document. getElementById ("msg"); var wsServer = 'Ws: // 192.168.1.253: 8080'; // call the websocket object to establish a connection: // parameter: ws/wss (encrypted ): // ip: port (string) var websocket = new WebSocket (wsServer); // onopen listener connection opens websocket. onopen = function (evt) {// websocket. readyState property:/* CONNECTING 0 The connection is not yet open. OPEN 1 The connection is open and ready to communicate. CLOSING 2 The connection is in the process of closing. CLOSED 3 The connection is closed or couldn't be opened. */msg. innerHTML = websocket. readyState;}; function song () {var text = document. getElementById ('text '). value; document. getElementById ('text '). value = ''; // send the websocket data to the server. send (text);} // listener connection closed // websocket. onclose = function (evt) {// console. log ("Disconnected"); //}; // onmessage listener server data push websocket. onmessage = function (evt) {msg. innerHTML + = evt. data +'
'; // Console. log ('Retrieved data from server: '+ evt. data) ;}; // listener connection error message // websocket. onerror = function (evt, e) {// console. log ('error occured: '+ evt. data); //}; script

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.