要应用键盘输入的一些知识如下例子:
- <?php
- fwrite(STDOUT, "Please input your name:\t");
- echo $name = trim(fgets(STDIN));
- fwrite(STDOUT, 'Hello ' . $name);
- ?>
点对点通信开始
1.SERVER
- <?php
- // 建立server端socket
- $tcp = getprotobyname("tcp");
- $socket = socket_create(AF_INET, SOCK_STREAM, $tcp);
- socket_bind($socket, '127.0.0.1', 10008); //绑定要监听的端口
- socket_listen($socket); //监听端口
- $connection = socket_accept($socket);
- if(!$connection){
- echo "connect fail";
- }
- $data = @socket_read($connection, 1024, PHP_NORMAL_READ);
- printf("Client: " . $data);
- //键盘输入信息
- while ($buffer= trim(fgets(STDIN))) {
- if($buffer =="bye") break;
- // 向客户端传递一个信息数据
- socket_write($connection, $buffer . "\n");
- // 从客户端取得信息
- $data = @socket_read($connection, 1024, PHP_NORMAL_READ);
- printf("Client : " . $data);
- }
- socket_close($connection);
- //关闭 socket
- printf("Closed the socket\n");
- ?>
2:CLIENT
- <?php
- // 建立客户端的socet连接
- $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
- $connection = socket_connect($socket, '127.0.0.1', 10008); //连接服务器端socket
- //键盘输入信息
- while ($data= trim(fgets(STDIN))) {
- if($data =="exit") break;
- // 将客户的信息写到通道中,传给服务器端
- if (!socket_write($socket, $data."\n")) {
- echo "Write failed\n";
- }
- //服务器端收到信息后,给于的回应信息
- $buffer = socket_read($socket, 1024, PHP_NORMAL_READ);
- if($buffer=="bye") break;
- echo "Server Data:" . $buffer;
- }
- ?>