要使用PHP的socket進行通信,你需要創建一個TCP或UDP客戶端/服務器應用程序。下面是一個簡單的例子,展示了如何創建一個基本的TCP客戶端和服務器。
1. 創建一個TCP服務器:
<?php
// 服務器地址和端口
$host = '127.0.0.1';
$port = 8080;
// 創建socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$socket) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
// 綁定地址和端口
socket_bind($socket, $host, $port);
// 監聽連接
socket_listen($socket, 3);
echo "Server is listening on $host:$port...\n";
// 接受客戶端連接
$client = socket_accept($socket);
if (!$client) {
echo "socket_accept() failed.\n";
exit();
}
// 讀取客戶端發送的數據
$input = socket_read($client, 2048);
echo "Received message: $input\n";
// 向客戶端發送響應
$response = "Hello from server!\n";
socket_write($client, $response);
// 關閉連接
socket_close($client);
socket_close($socket);
?>
2. 創建一個TCP客戶端:
<?php
// 服務器地址和端口
$host = '127.0.0.1';
$port = 8080;
// 創建socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$socket) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
// 連接到服務器
socket_connect($socket, $host, $port);
// 向服務器發送數據
$message = "Hello from client!\n";
socket_write($socket, $message);
// 讀取服務器發送的響應
$response = socket_read($socket, 2048);
echo "Received response: $response\n";
// 關閉連接
socket_close($socket);
?>
3. 創建一個UDP客戶端和服務器:
UDP服務器:
<?php
// 服務器地址和端口
$host = '127.0.0.1';
$port = 8080;
// 創建socket
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if (!$socket) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
// 綁定地址和端口
socket_bind($socket, $host, $port);
echo "Server is listening on $host:$port...\n";
// 接收客戶端數據
$data = socket_read($socket, 2048);
$sender = socket_getpeername($socket);
echo "Received message from $sender: $data\n";
// 向客戶端發送響應
$response = "Hello from server!\n";
socket_write($socket, $response, strlen($response));
// 關閉連接
socket_close($socket);
?>
UDP客戶端:
<?php
// 服務器地址和端口
$host = '127.0.0.1';
$port = 8080;
// 創建socket
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if (!$socket) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
// 向服務器發送數據
$message = "Hello from client!\n";
$length = strlen($message);
socket_write($socket, $message, $length);
// 讀取服務器發送的響應
$data = socket_read($socket, 2048);
echo "Received response: $data\n";
// 關閉連接
socket_close($socket);
?>
運行這些腳本,首先啟動服務器,然后啟動客戶端。你應該看到服務器和客戶端之間的通信。根據需要修改地址、端口和數據。