要使用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);
?>
运行这些脚本,首先启动服务器,然后启动客户端。你应该看到服务器和客户端之间的通信。根据需要修改地址、端口和数据。