Php socket push technology example, phpsocket push example

Source: Internet
Author: User

Php socket push technology example, phpsocket push example

Before the emergence of the socket, there were ajax scheduled requests, long polling and other solutions, but none of them could meet the requirements, and the socket was applied.

Socket basic function socket

Summary of common socket Functions

Server:Socket_create create socket settings Basic parameters

Socket_bind: bind ip address and port number

Socket_listen listener

Socket_accept Client Connection

Socket_read reads client data

Socket_write sends data to a separate client

Socket_close close connection

Client:Socket_create create socket settings Basic parameters

Socket_connect connects to socket

Socket_write sends data to the server

Socket_read reads server data

Socket_close close connection

H5websocket is not mentioned anymore.

OK, start pasting code ~

------------------------------------------------------------ Split line

Server code:

<? Phpclass WS {var $ master; var $ sockets = array (); var $ debug = false; // true indicates the debugging mode and outputs the log var $ handshake = array (); function _ construct ($ address, $ port) {$ this-> master = socket_create (AF_INET, SOCK_STREAM, SOL_TCP) or die ("socket_create () failed "); socket_set_option ($ this-> master, SOL_SOCKET, SO_REUSEADDR, 1) or die ("socket_option () failed"); socket_bind ($ this-> master, $ address, $ port) or die ("socke T_bind () failed "); socket_listen ($ this-> master, 20) or die (" socket_listen () failed "); $ this-> sockets [] = $ this-> master; $ this-> say ("Server Started :". date ('Y-m-d H: I: s'); $ this-> say ("Listening on :". $ address. "port ". $ port); $ this-> say ("Master socket :". $ this-> master. "\ n"); while (true) {$ socketArr = $ this-> sockets; $ write = NULL; $ except = NULL; socket_select ($ socketArr, $ write, $ locale T, NULL ); // Automatically select the socket for the message. if it is a handshake, automatically select the host foreach ($ socketArr as $ socket) {if ($ socket = $ this-> master) {// host $ client = socket_accept ($ this-> master); if ($ client <0) {$ this-> log ("socket_accept () failed "); continue;} else {$ this-> connect ($ client) ;}} else {$ bytes = @ socket_recv ($ socket, $ buffer, 2048,0 ); if ($ bytes = 0) {$ this-> disConnect ($ socket);} else {$ key = array_search ($ socket, $ this-> sockets); if (Empty ($ this-> handshake) |! Isset ($ this-> handshake [$ key]) |! $ This-> handshake [$ key]) {$ this-> doHandShake ($ socket, $ buffer, $ key );} else {$ buffer = $ this-> decode ($ buffer); echo $ buffer. PHP_EOL; $ key = array_search ($ socket, $ this-> sockets); $ arr = $ this-> sockets; array_shift ($ arr); foreach ($ arr as $ s) {$ this-> send ($ s, $ buffer) ;}}}} function send ($ client, $ msg) {$ msg = $ this-> frame ($ msg); socket_write ($ client, $ msg, strlen ($ msg);} function connect ($ Socket) {array_push ($ this-> sockets, $ socket); $ this-> say ("\ n". $ socket. "CONNECTED! "); $ This-> say (date (" Y-n-d H: I: s ");} function disConnect ($ socket) {$ index = array_search ($ socket, $ this-> sockets); socket_close ($ socket); $ this-> say ($ socket. "DISCONNECTED! "); If ($ index> = 0) {echo 'unset index is :'. PHP_EOL; unset ($ this-> sockets [$ index]);} function doHandShake ($ socket, $ buffer, $ handKey) {$ this-> log ("\ nRequesting handshake... "); $ this-> log ($ buffer); list ($ resource, $ host, $ origin, $ key) = $ this-> getHeaders ($ buffer ); $ this-> log ("Handshaking... "); $ upgrade =" HTTP/1.1 101 Switching Protocol \ r \ n ". "Upgrade: websocket \ r \ n ". "Connection: Upgrade \ r \ n ". "Sec-WebSocket-Accept :". $ this-> calcKey ($ key ). "\ r \ n"; // It must end with two carriage returns $ this-> log ($ upgrade); $ sent = socket_write ($ socket, $ upgrade, strlen ($ upgrade); $ this-> handshake [$ handKey] = true; $ this-> log ("Done handshaking... "); return true;} function getHeaders ($ req) {$ r = $ h = $ o = $ key = null; if (preg_match ("/GET (. *) HTTP/", $ req, $ match) {$ r = $ match [1];} if (preg_match ("/Host :(. *) \ r \ n/", $ req, $ match) {$ h = $ match [1];} if (preg_match ("/Origin :(. *) \ r \ n/", $ req, $ match) {$ o = $ match [1];} if (preg_match ("/Sec-WebSocket-Key: (. *) \ r \ n/", $ req, $ match) {$ key = $ match [1];} return array ($ r, $ h, $ o, $ key);} function calcKey ($ key) {// Based on websocket version 13 $ accept = base64_encode (sha1 ($ key. '258eafa5-E914-47DA-95CA-C5AB0DC85B11 ', true); return $ accept;} function decode ($ buffer) {$ len = $ masks = $ data = $ decoded = null; $ len = ord ($ buffer [1]) & 127; if ($ len = 126) {$ masks = substr ($ buffer, 4, 4 ); $ data = substr ($ buffer, 8);} else if ($ len = 127) {$ masks = substr ($ buffer, 10, 4 ); $ data = substr ($ buffer, 14);} else {$ masks = substr ($ buffer, 2, 4); $ data = substr ($ buffer, 6 );} for ($ index = 0; $ index <strlen ($ data); $ index ++) {$ decoded. = $ data [$ index] ^ $ masks [$ index % 4];} return $ decoded;} function frame ($ s) {$ a = str_split ($ s, 125); if (count ($ a) = 1) {return "\ x81 ". chr (strlen ($ a [0]). $ a [0] ;}$ ns = ""; foreach ($ a as $ o) {$ ns. = "\ x81 ". chr (strlen ($ o )). $ o;} return $ ns;} function say ($ msg = "") {echo $ msg. "\ n";} function log ($ msg = "") {if ($ this-> debug) {echo $ msg. "\ n" ;}}} new WS ('localhost', 4000 );

Client code (H5 ):

<Html> 

Then execute php demo. php to enable the socket (from the O & M, you can steal a trick. in linux, execute nohup php demo. php &&, and you can execute an issue later. The browser opens multiple index.html files to establish communication.

Code parsing:

1. Attribute $ sockets array saves each accept connection (I do not know if this description is correct );

2. Attribute $ handshake array: whether the connection is in the connection status;

The above example of implementing the socket push technology in php is all the content shared by xiaobian. I hope you can give us a reference and support the help house.

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.