server:
1 <?php 2 set_time_limit(0); 3 4 $ip = '127.0.0.1'; 5 $port = 8888; 6 7 // 1. 創建 8 if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == FALSE ){ 9 echo 'create fail:' . socket_strerror(socket_last_error()); 10 } 11 12 // 2. 綁定 13 if ( socket_bind($sock, $ip, $port) == FALSE ) { 14 echo 'bind fail:' . socket_strerror(socket_last_error()); 15 } 16 17 // 3. 監聽 18 if( socket_listen($sock, 4) == FALSE ){ 19 echo 'listen fail:' . socket_strerror(socket_last_error()); 20 } 21 22 $count = 0; 23 24 do{ 25 // 4. 阻塞,等待客戶端請求 26 if ( ($msgsock = socket_accept($sock)) == FALSE ) { 27 28 echo 'accept fail:' . socket_strerror(socket_last_error()); 29 30 break; 31 } else { 32 33 // 5. 向客戶端寫入信息 34 $msg = 'server send successfully!'; 35 socket_write($msgsock, $msg, strlen($msg)); 36 37 38 // 5. 讀取客戶端信息 39 echo '-----test successfully!------'; 40 $buf = socket_read($msgsock, 8192); 41 42 43 $talkback = 'receive client: ' . $buf; 44 echo $talkback; 45 46 47 if ($count >= 5) { 48 break; 49 } 50 } 51 52 // 6. 關閉socket 53 socket_close($msgsock); 54 55 }while(true); 56 57 // 6. 關閉socket 58 socket_close($sock);
client:
<?php error_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.';