My websocket demo (php server) and websocketdemo

Source: Internet
Author: User

My websocket demo (php server) and websocketdemo

Notice:

Execute the php file through the command line, such as php-q c: \ path \ server. php.

Access http: // 127.0.0.1/websocket/index. php through a local web server.

Notice:
Php5.3 or above is required, and a web server such as apache
The browser must support html5 web socket
Listen to socket port 9505 here. If the port is occupied, you may need to modify the port or kill the corresponding port process in the two files.

The mobile phone on the page looks better than on the pc!

1. client code html file

1. client code: <! DOCTYPE html>  

2. php file of socket server code

2. php code: <? Php $ host = '2017. 0.0.1 '; $ port = '000000'; $ null = NULL; // create a tcp socket $ socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option ($ socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind ($ socket, 0, $ port); // listening port socket_listen ($ socket ); // list of connected client sockets $ clients = array ($ socket); // sets an endless loop for listening to connections. The status is while (true) {$ changed = $ clients; socket_select ($ changed, $ null, $ null, 0, 10); // if there is a new connection if (in_array ($ socket, $ changed )) {// accept and add a new socket connection $ socket_new = socket_accept ($ socket); $ clients [] = $ socket_new; // execute handshake $ header = socket_read ($ socket_new, 1024) to obtain data through the socket; then m_handshaking ($ header, $ socket_new, $ host, $ port ); // obtain the client ip encoded json data and send a notification socket_getpeername ($ socket_new, $ ip); $ response = mask (json_encode (array ('type' => 'system ', 'message' => $ ip. 'connected'); send_message ($ response); $ found_socket = array_search ($ socket, $ changed); unset ($ changed [$ found_socket]);} // poll each client socket to connect to foreach ($ changed as $ changed_socket) {// If client data is sent over while (socket_recv ($ changed_socket, $ buf, 1024, 0)> = 1) {// decodes the sent data $ received_text = unmask ($ buf); $ tst_msg = json_decode ($ received_text); $ user_name = $ tst_msg-> name; $ user_message = $ tst_msg-> message; // send the message back to all connected clients $ response_text = mask (json_encode (array ('type' => 'usermsg ', 'name' => $ user_name, 'message' => $ user_message); send_message ($ response_text); break 2 ;} // check the offline client $ buf = @ socket_read ($ changed_socket, 1024, PHP_NORMAL_READ); if ($ buf === false) {$ found_socket = array_search ($ changed_socket, $ clients); socket_getpeername ($ changed_socket, $ ip); unset ($ clients [$ found_socket]); $ response = mask (json_encode (array ('type' => 'system', 'message' => $ ip. 'disconnected'); send_message ($ response) ;}}// disable socketsocket_close ($ sock) of the listener; // function send_message ($ msg) of the message sending Method) {global $ clients; foreach ($ clients as $ changed_socket) {@ socket_write ($ changed_socket, $ msg, strlen ($ msg);} return true ;} // decodes data function unmask ($ text) {$ length = ord ($ text [1]) & 127; if ($ length = 126) {$ masks = substr ($ text, 4, 4); $ data = substr ($ text, 8);} elseif ($ length = 127) {$ masks = substr ($ text, 10, 4); $ data = substr ($ text, 14);} else {$ masks = substr ($ text, 2, 4); $ data = substr ($ text, 6);} $ text = ""; for ($ I = 0; $ I <strlen ($ data ); ++ $ I) {$ text. = $ data [$ I] ^ $ masks [$ I % 4];} return $ text;} // encode the data function mask ($ text) {$ b1 = 0x80 | (0x1 & 0x0f); $ length = strlen ($ text); if ($ length <= 125) $ header = pack ('cc', $ b1, $ length); elseif ($ length> 125 & $ length <65536) $ header = pack ('ccn ', $ b1, 126, $ length); elseif ($ length> = 65536) $ header = pack ('ccnn ', $ b1, 127, $ length); return $ header. $ text;} // logic function of handshaking m_handshaking ($ receved_header, $ client_conn, $ host, $ port) {$ headers = array (); $ lines = preg_split ("/\ r \ n/", $ receved_header); foreach ($ lines as $ line) {$ line = chop ($ line ); if (preg_match ('/\ A (\ S + ):(. *) \ z/', $ line, $ matches) {$ headers [$ matches [1] = $ matches [2];} $ secKey = $ headers ['sec-WebSocket-key']; $ secAccept = base64_encode (pack ('H * ', sha1 ($ secKey. '258eafa5-E914-47DA-95CA-C5AB0DC85B11 '); $ upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake \ r \ n ". "Upgrade: websocket \ r \ n ". "Connection: Upgrade \ r \ n ". "WebSocket-Origin: $ host \ r \ n ". "WebSocket-Location: ws: // $ host: $ port/demo/shout. php \ r \ n ". "Sec-WebSocket-Accept: $ secAccept \ r \ n"; socket_write ($ client_conn, $ upgrade, strlen ($ upgrade ));}View Code

 

In the future, I will make a full copy of the java version.

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.