I do a websocket demo (PHP server), websocketdemo_php tutorial

Source: Internet
Author: User
Tags php server

I do a websocket demo (PHP server), Websocketdemo


Notice

Execute PHP files from the command line such as Php-q c:\path\server.php

Access http://127.0.0.1/websocket/index.php from a local Web server

Notice
Requires php5.3 or more of the execution environment, and a Web server such as Apache
Browsers need to support HTML5 Web sockets
This listens to socket port 9505, which may need to modify the port within these two files or kill the corresponding port process if the port is encountered

The page looks better on the phone than on the PC!

1. Client-side code HTML file

1 . Client code: <title>Chatdemo</title> " Utf-8 "> " Viewport "Content= " width=device-width,initial-scale=1, maximum-scale=1, User-scalable=no "> " Https://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css "Rel= " stylesheet "> Class= " Container "> class= " title "> Simple Chat Demo class= " content "> class= " Show-area "> class= " Write-area "> class="btn btn-defaultsend" > Send " name "Id= " name "Type= " text "Placeholder= " Input your name "> <textarea name="<span">"</span><span>message</span><span>" </span> id=<span> "</span>< Span>message</span><span> "</span> cols=<span>" </span><span>38</span ><span> "</span> rows=<span>" </span><span>4</span><span> "</span > placeholder=<span> "</span><span>input your message...</span><span>" </span >></textarea> View Code

2.socket server-side code PHP file

2 . PHP Code: Php$host= ' 127.0.0.1 ' ; $port= ' 9505 ' ; $ 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); // Connected client Socket list$clients = Array ($socket); // set a dead loop to listen for connections, status while( true ) {$changed= $clients; Socket_select ($changed, $ NULL, $ NULL, 0, Ten ); // 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; // get Data execution handshake via socket$header = Socket_read ($socket _new, 1024x768 ); Perform_handshaking ($header, $socket _new, $host, $port); // get the client IP encoded JSON data and send notifications 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 connection foreach($changed as $changed _socket) { // If you have client data sent over while(Socket_recv ($changed _socket, $buf, 1024x768, 0) >= 1 ) { // decode the data sent over$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 offline's client$buf = @socket_read ($changed _socket, 1024x768 , 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); } }} // turn off the listening socket Socket_close ($sock); // ways to send messages function Send_message ($msg) { Global $clients; foreach($clients as $changed _socket) {@socket_write ($changed _socket, $msg, strlen ($msg));} return true ;} // Decoding 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, Ten, 4 ); $data= substr ($text, - ); } 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;} // coded Data function Mask ($text) {$b 1= 0x80| ( 0x1& 0x0f ); $length= strlen ($text); if($length <= the ) $header= Pack ( ' CC ' , $b 1, $length); ElseIf ($length> the&& $length < 65536 ) $header= Pack ( ' CCn ', $b 1, 126 , $length); ElseIf ($length>= 65536 ) $header= Pack ( ' CCNN ', $b 1, 127 , $length); return $header. $text;} // the logic of shaking hands function perform_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\r\n " ; Socket_write ($client _conn, $upgrade, strlen ($upgrade));} View Code

You will be free to complete the Java version later.

http://www.bkjia.com/PHPjc/1100393.html www.bkjia.com true http://www.bkjia.com/PHPjc/1100393.html techarticle I do a websocket demo (PHP server), Websocketdemo Notice: Execute PHP files via the command line such as Php-q c:\path\server.php access via local Web server/HTTP/ 127.0.0.1/web ...

  • 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.