phpsocket 簡單的php socket 執行個體

來源:互聯網
上載者:User
server:

 1 php 2set_time_limit(0); 3 4$ip = '127.0.0.1'; 5$port = 8888; 6 7// 1. 建立 8if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == FALSE ){ 9echo 'create fail:' . socket_strerror(socket_last_error());10}1112// 2. 綁定13if ( socket_bind($sock, $ip, $port) == FALSE ) {14echo 'bind fail:' . socket_strerror(socket_last_error());15}1617// 3. 監聽18if( socket_listen($sock, 4) == FALSE ){19echo 'listen fail:' . socket_strerror(socket_last_error());20}2122$count = 0;2324do{25// 4. 阻塞,等待用戶端請求26if ( ($msgsock = socket_accept($sock)) == FALSE ) {2728echo 'accept fail:' . socket_strerror(socket_last_error());2930break;31     } else {3233// 5. 向用戶端寫入資訊34$msg = 'server send successfully!';35         socket_write($msgsock, $msg, strlen($msg));363738// 5. 讀取用戶端資訊39echo '-----test successfully!------';40$buf = socket_read($msgsock, 8192);414243$talkback = 'receive client: ' . $buf;44echo$talkback;454647if ($count >= 5) {48break;49        }50    }5152// 6. 關閉socket53     socket_close($msgsock);5455 }while(true);5657// 6. 關閉socket58 socket_close($sock);

client:

phperror_reporting(E_ALL);set_time_limit(0);$ip = '127.0.0.1';$port = 8888;// 1. 建立$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);if( $socket == FALSE ) {    echo 'create fail: ' . socket_strerror(socket_last_error());} else {    echo 'OK';}// 2. 連結echo 'we will try to connect ' . $ip .':' . $port . '\r\n----';$result = socket_connect($socket, $ip, $port);if ( $result == FALSE) {    }$in = 'HO ';$in .= 'first blood--------';$out = '';// 3. 向服務端寫入if( !socket_write($socket, $in, strlen($in)) ) {    echo 'write fail: ' . socket_strerror(socket_last_error());} else {    echo '-----send to server succefully! \r\n----';    echo 'the content is ' . $in;}// 3. 從服務端讀取while ( $out = socket_read($socket, 8129) ) {    echo '-----receive from server succefully!\r\n------';    echo 'the contents is ' . $out;}// 4. 關閉echo '----close socket ...';socket_close($socket);echo 'closed ok.';

以上就介紹了phpsocket 簡單的php socket 執行個體,包括了phpsocket方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.