-
- error_reporting(E_ALL);
- set_time_limit(0);
- echo "
TCP/IP Connectionn";
-
- $port = 1935;
- $ip = "127.0.0.1";
-
- /*
- +-------------------------------
- * @socket连接整个过程
- +-------------------------------
- * @socket_create
- * @socket_connect
- * @socket_write
- * @socket_read
- * @socket_close
- +--------------------------------
- */
-
- $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
- if ($socket < 0) {
- echo "socket_create() failed: reason: " . socket_strerror($socket) . "n";
- }else {
- echo "OK.n";
- }
-
- echo "试图连接 '$ip' 端口 '$port'...n";
- $result = socket_connect($socket, $ip, $port);
- if ($result < 0) {
- echo "socket_connect() failed.nReason: ($result) " . socket_strerror($result) . "n";
- }else {
- echo "连接OKn";
- }
-
- $in = "Horn";
- $in .= "first bloodrn";
- $out = '';
-
- if(!socket_write($socket, $in, strlen($in))) {
- echo "socket_write() failed: reason: " . socket_strerror($socket) . "n";
- }else {
- echo "发送到服务器信息成功!n";
- echo "发送的内容为:$in
";
- }
-
- while($out = socket_read($socket, 8192)) {
- echo "接收服务器回传信息成功!n";
- echo "接受的内容为:",$out;
- }
-
- echo "关闭SOCKET...n";
- socket_close($socket);
- echo "关闭OKn";
- ?>
复制代码
服务器端代码:
-
- //确保在连接客户端时不会超时
- set_time_limit(0);
-
- $ip = '127.0.0.1';
- $port = 1935;
-
- /*
- +-------------------------------
- * @socket通信整个过程
- +-------------------------------
- * @socket_create
- * @socket_bind
- * @socket_listen
- * @socket_accept
- * @socket_read
- * @socket_write
- * @socket_close
- +--------------------------------
- */
-
- /*----------------以下操作都是手册上的-------------------*/
- if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
- echo "socket_create() 失败的原因是:".socket_strerror($sock)."n";
- }
-
- if(($ret = socket_bind($sock,$ip,$port)) < 0) {
- echo "socket_bind() 失败的原因是:".socket_strerror($ret)."n";
- }
-
- if(($ret = socket_listen($sock,4)) < 0) {
- echo "socket_listen() 失败的原因是:".socket_strerror($ret)."n";
- }
-
- $count = 0;
-
- do {
- if (($msgsock = socket_accept($sock)) < 0) {
- echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "n";
- echo "等待连接...";
- break;
- } else {
-
- //发到客户端
- $msg ="测试成功!n";
- socket_write($msgsock, $msg, strlen($msg));
-
- echo "测试成功了啊n";
- $buf = socket_read($msgsock,8192);
-
- $talkback = "收到的信息:$bufn";
- echo $talkback;
-
- if(++$count >= 5){
- break;
- };
- }
- //echo $buf;
- socket_close($msgsock);
-
- } while (true);
-
- socket_close($sock);
- ?>
-
复制代码
|
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31