您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關怎么用PHP中socket實現客戶端到服務端的通信,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
一、server.php服務端:
<?php error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); //本地IP $address = 'localhost'; //設置用111端口進行通信 $port = 111; //創建SOCKET if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) { echo "socket創建失敗原因 " . socket_strerror($sock) . "\n"; } if (($ret = socket_bind($sock, $address, $port)) < 0) { echo "創建套接字失敗原因 " . socket_strerror($ret) . "\n"; } //監聽 if (($ret = socket_listen($sock, 5)) < 0) { echo "監聽失敗原因 " . socket_strerror($ret) . "\n"; } do { //接收命令 if (($msgsock = @socket_accept($sock)) < 0) { echo "命令接收失敗原因: " . socket_strerror($msgsock) . "\n"; break; } $msg = "\nPHP Test Server. \n" ."用quit,shutdown,sun...等命令測試.\n"; @socket_write($msgsock, $msg, strlen($msg)); do { if (false === ($buf = @socket_read($msgsock, 2048, PHP_NORMAL_READ))) { echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n"; break 2; } if (!$buf = trim($buf)) { continue; } if ($buf == 'quit') { break; } if ($buf == 'shutdown') { socket_close($msgsock); break 2; } if ($buf == 'sun') { echo'what are you doing?'; } $talkback = "Backinformation : '$buf'.\n"; socket_write($msgsock, $talkback, strlen($talkback)); echo "$buf\n"; } while (true); socket_close($msgsock); } while (true); socket_close($sock); ?>
二、client.php客戶端:
<?php error_reporting(E_ALL); //端口111 $service_port = 111; //本地 $address = 'localhost'; //創建 TCP/IP socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket < 0) { echo "socket創建失敗原因: " . socket_strerror($socket) . "\n"; } else { echo "OK,HE HE.\n"; } $result = socket_connect($socket, $address, $service_port); if ($result < 0) { echo "SOCKET連接失敗原因: ($result) " . socket_strerror($result) . "\n"; } else { echo "OK.\n"; } //發送命令 $in = "HEAD / HTTP/1.1\r\n"; $in .= "Connection: Close\r\n\r\n"; $out = ''; echo "Send Command.........."; $in = "sun\n"; socket_write($socket, $in, strlen($in)); echo "OK.\n"; echo "Reading Backinformatin:\n\n"; while ($out = socket_read($socket, 2048)) { echo $out; } echo "Close socket........"; socket_close($socket); echo "OK,He He.\n\n"; ?>
這兩段代碼是簡單介紹用PHP實現客戶端和服務端的通信
具體操作,在DOS下用PHP命令打開SERVER,處于監聽狀態..
再打開一個DOS窗口,用PHP命令打開CLIENT,會得到服務端的回應....
關于“怎么用PHP中socket實現客戶端到服務端的通信”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。