Windows centos 程序员 linux Firefox linux命令 wordpress HTML5 微软 Python mysql nginx Android 开源 Ubuntu php java apache google shell

php-socket简单应用

服务端代码

<?PHP
set_time_limit(0);
$host = "192.168.8.226";
$port = 1234;


// 创建一个Socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socketn");

//绑定Socket到端口
$result = socket_bind($socket, $host, $port) or die("Could not bind to socketn");

// 开始监听链接
$result = socket_listen($socket, 3) or die("Could not set up socket listenern");

//socket_set_nonblock($socket);

 while(1){

        // accept incoming connections

        // 另一个Socket来处理通信,每一个客户端连接过来都会创建一个新的socket

        $spawn = socket_accept($socket) or die("Could not accept incoming connectionn");

        while($input = socket_read($spawn, 1024)){

                // 清空输入字符串

                $input = trim($input)."n";

                //处理客户端输入并返回结果

                error_log($input, 3, './write_file.txt');

                $times ++;

                $output = "write file success $times times";

                socket_write($spawn, $output, strlen ($output)) or die("Could not write outputn");

        }

        socket_close($spawn);

}

 // 关闭sockets

socket_close($socket);

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

客户端代码

<?php

$service_port = 1234;

$address = '192.168.8.226';

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

$result = socket_connect($socket, $address, $service_port);

 
$in = 1234;

socket_write($socket, $in, strlen($in));


 
while ($out = socket_read($socket, 8192)) {

        echo $out."n";

        $in++;

        socket_write($socket, $in, strlen($in));

        sleep(2);

}

socket_close($socket);

延伸阅读

评论