$port = isset($argv[2]) ? $argv[2] : "123654"; // 第2步:创建socket $sock_cli = @socket_create(AF_INET, SOCK_STREAM, 0); // SOL_TCP // 第3步:连接服务器---connect if (false == socket_connect($sock_cli, $host, $port)) { print_sock_err($sock_cli, "CONNECT"); } while (1) { // 第4步,写入命令请求 $data = fgets(STDIN); $len = socket_write($sock_cli, $data, strlen($data)); if ($len < 0) { print_sock_err($sock_cli, "WRITE"); exit; } // 第5步,读取返回结果 $response = socket_read($sock_cli, MAX_STR_LEN); if ($len < 0) { print_sock_err($sock_cli, "READ"); exit; } fwrite(STDOUT, $response); } function print_sock_err($sock, $type) { $errno = socket_last_error($sock); $errmsg = socket_strerror($errno); echo "{$type} ERROR:{$errno} - {$errmsg}" . PHP_EOL; socket_close($sock); }
function connectLocalSocket($local_socket_file) { $socket_cli = socket_create(AF_UNIX, SOCK_STREAM, 0); if ($socket_cli === false) { print_sock_err($socket_cli, "CREATE"); socket_close($socket_cli); exit; } if (false === @socket_connect($socket_cli, $local_socket_file)) { print_sock_err($socket_cli, "LISTEN"); socket_close($socket_cli); exit; } return $socket_cli; }
function sendResponseToClient($sock, $request) { $arguments = preg_split('/[\\n\\r\\t\\s]+/i', $request); $cmd = array_shift($arguments); if ($cmd == "exit") { socket_close($sock); exit; } $handler = "{$cmd}CommandHandler"; if (function_exists($handler)) { $response = call_user_func_array($handler, $arguments); $response .= PHP_EOL; } else { $response = $request; } // 解析客户端发送来的data,并且将处理结果进行response //$response = fgets(STDIN); // 第7步:发送消息给客户端socket---send if (socket_send($sock, $response, strlen($response), 0) == false) { print_sock_err($sock, "WRITE"); exit; } }