欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP+SOCKET例证

程序员文章站 2024-02-12 10:01:52
...
PHP+SOCKET例子
// Client // 设置错误处理error_reporting (E_ALL);// 设置处理时间set_time_limit (0);$ip = "";       // IP 地址$port = 1000;            // 端口号$socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);   // 创建一个SOCKETif ($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";echo socket_read ($socket, 1024)."
";$stdin = fopen ('php://stdin', 'r');$ar = array("HELLO","HELP","test","QUIT");$i = 0;while (true){// $command = trim (fgets ($stdin, 1024));// socket_write ($socket, $command, strlen ($command));echo "发送 $ar[$i]
"; socket_write ($socket, $ar[$i], strlen($ar[$i]));$i++; $msg = trim (socket_read ($socket, 1024)); echo "收到:$msg
\n"; if ($msg == "Bye-Bye") break;}fclose ($stdin);socket_close ($socket);

?

?

?

?

?

?

?

?

======================================

?

?

// Server// 设置错误处理error_reporting (E_ALL);// 设置运行时间set_time_limit (0);// 起用缓冲ob_implicit_flush ();$ip = "";        // IP地址$port = 1000;             // 端口号$socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP);       // 创建一个SOCKETif ($socket)    echo "socket_create() successed!\n";else    echo "socket_create() failed:".socket_strerror ($socket)."\n";$bind = socket_bind ($socket, $ip, $port);              // 绑定一个SOCKETif ($bind)    echo "socket_bind() successed!\n";else    echo "socket_bind() failed:".socket_strerror ($bind)."\n";$listen = socket_listen ($socket);                 // 间听SOCKETif ($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;    }    $welcome = "服务端收到:Welcome to PHP Server!\n";    socket_write ($msg, $welcome, strlen ($welcome));    while (true)    {        $command = strtoupper (trim (socket_read ($msg, 1024)));        if (!$command)            break;        switch ($command)        {            case "HELLO":                $writer = "Hello Everybody!";                break;            case "QUIT":                $writer = "Bye-Bye";                break;            case "HELP":                $writer = "HELLO\tQUIT\tHELP";                break;            default:                $writer = "Error Command!";        }        socket_write ($msg, $writer, strlen ($writer));        if ($command == "QUIT")            break;    }    socket_close ($msg);    if ($command == "QUIT")        break;}socket_close ($socket);                   // 关闭SOCKET

?

?

PHP+SOCKET例证

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

相关文章

相关视频