分类: PHP
2013-01-31 11:45:15
服务器端程序:server.php
#! /usr/bin/php
function server()
{
$ip = "127.0.0.1"; // IP地址
$port = 8000; // 端口号
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 创建一个SOCKET
if ($socket)
echo "socket_create successed!\n";
else
echo "socket_create failed:".socket_strerror ($socket)."\n";
$bind = socket_bind($socket, $ip, $port);
if ($bind)
echo "socket_bind successed!\n";
else
echo "socket_bind failed:".socket_strerror ($bind)."\n";
socket_listen($socket,5); // 间听SOCKET
while (true)
{
$client = socket_accept($socket); // 接受一个SOCKET
echo "connect a new client $client\n";
$pidf =pcntl_fork();
if($pidf<0)
{
echo "first fork error\n";
}elseif($pidf == 0)
{
$pid = pcntl_fork();
if($pid<0)
{
echo "second fork error\n";
}elseif($pid == 0)
{
while (true)
{
$command = trim(socket_read($client, 1024));
$return = socket_getpeername ($client,$clientip,$clientport);
if($return == FALSE)
{
echo "get remote ip port false\n";
}
echo "客户端 ip:$clientip 端口是: $clientport 发送过来的信息是: $command\n";
if (!$command)
break;
switch ($command)
{
case "quit":
$writer = "Bye-Bye";
break;
default:
$writer = "Server has recived the message is $command!\n";
}
socket_write($client, $writer, strlen($writer));
if ($command == "quit")
break;
}
if ($command == "quit")
{
echo "Close the client $client\n";
socket_close($client);
exit();
//posix_kill(getmypid(), SIGKILL),
//pcntl_wait($pid);
//break;
}
}elseif($pid>0)
{
exit();
}
}elseif($pidf>0)
{
pcntl_wait($pid);
}
}
socket_close($socket); // 关闭SOCKET
}
server();
?>
客户端程序:client.php
function client()
{
$ip = "127.0.0.1"; // IP 地址
$port = 8000; // 端口号
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 创建一个SOCKET
if ($socket)
echo "socket_create() 成功!\n";
else
echo "socket_create() 失败:".socket_strerror ($socket)."\n";
$conn = socket_connect($socket, $ip, $port);// 建立SOCKET的连接
if ($conn)
echo "成功连接到[".$ip.":".$port."]\n";
else
echo "socket_connect() 失败:".socket_strerror ($conn)."\n";
while (true)
{
echo "请输入你想要发送的信息,输入 quit 将会断开此次连接\n";
$command = trim(fgets(STDIN));
socket_write($socket, $command, strlen ($command));
$msg = trim(socket_read($socket, 1024));
echo "收到:$msg\n";
if ($msg == "Bye-Bye")
break;
}
fclose(STDIN);
socket_close($socket);
}
client();
?>