【socket】用PHP的socket實現客戶端到服務端的通訊
1、server.php服務端:php
- <?php
- error_reporting(E_ALL);
- set_time_limit(0);
- ob_implicit_flush();
-
- $address = 'localhost';
-
- $port = 111;
-
- 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);
- ?>
2、client.php客戶端:
- <?php
- error_reporting(E_ALL);
-
- $service_port = 111;
-
- $address = 'localhost';
-
- $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實現客戶端和服務端的通訊
client.php
server.php
具體操做,在DOS下用PHP命令打開SERVER,處於監聽狀態..
再打開一個DOS窗口,用PHP命令打開CLIENT,會獲得服務端的迴應....
歡迎關注本站公眾號,獲取更多信息