[PHP socket]完整的示例,在Windows下调试通过

jackxiang 2008-5-30 14:50 | |
server.php:(UTF8编码)
<?php
// server
// 设置错误处理
error_reporting (e_all);
// 设置运行时间
set_time_limit (0);
// 起用缓冲
ob_implicit_flush ();
$ip = "127.0.0.1"; // ip地址
$port = 8848;  // 端口号
$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";
exit(0);
}

$bind = socket_bind ($socket, $ip, $port); // 绑定一个socket
if ($bind) {
  echo "socket_bind() successed!\n";
      }else{
        echo "socket_bind() failed:".socket_strerror ($bind)."\n";
        return 0;
       }

$listen = socket_listen ($socket);  // 间听socket
if ($listen)
echo "socket_listen() successed!\n";
else
echo "socket_listen() failed:".socket_strerror ($listen)."\n";

while (true)
{
$msg = socket_accept ($socket);  // 接受一个socket
if (!$msg)
{
echo "socket_accept() failed:".socket_strerror ($msg)."\n";
break;
}
$welcome0 = "welcome to php server!向东\n";
$welcome = iconv("utf-8","gbk",$welcome0);//显示gb的中文,否则在windows cmd 终端显示乱码
socket_write ($msg, $welcome, strlen ($welcome));
while (true)
{
$command = strtoupper (trim (socket_read ($msg, 1024)));
if (!$command)
break;
echo $command."\n";
switch ($command)
{
case "HELLO":
$writer = "hello everybody!";
break;
case "BYE":
$writer = "bye-bye";
break;
case "HELP":
$writer = "hello\tquit\thelp";
break;
default:
$writer = "error command!\n";
}
socket_write ($msg, $writer, strlen ($writer));
if ($command == "QUIT")
break;
}
socket_close ($msg);
}
socket_close ($socket);  // 关闭socket
?>
client.php(UTF8编码)
<?php
// Client
// 设置错误处理
error_reporting (E_ALL);
// 设置处理时间
set_time_limit (0);

$ip = "127.0.0.1";       // IP 地址
$port = 8848;            // 端口号

$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";

$conn = socket_connect ($socket, $ip, $port);       // 建立SOCKET的连接
if ($conn)
    echo "Success to connection![".$ip.":".$port."]/n";
else
    echo "socket_connect() failed:".socket_strerror ($conn)."/n";

echo socket_read ($socket, 1024);  

$stdin = fopen ('php://stdin', 'r');
while (true)
{
    $command = trim (fgets ($stdin, 1024));
    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);
?>

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/1059/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]