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

用PHP的socket实现客户端到服务端的通信实例详解

程序员文章站 2024-03-13 22:17:46
一、server.php服务端:

一、server.php服务端:

<?php 
error_reporting(e_all); 
set_time_limit(0); 
ob_implicit_flush(); 
//本地ip 
$address = 'localhost'; 
//设置用111端口进行通信 
$port = 111; 
//创建socket 
if (($sock = socket_create(af_inet, sock_stream, sol_tcp)) < 0) { 
    echo "socket创建失败原因 " . socket_strerror($sock) . "\n"; 
} 
 
if (($ret = socket_bind($sock, $address, $port)) < 0) { 
    echo "创建套接字失败原因 " . socket_strerror($ret) . "\n"; 
} 
//监听 
if (($ret = socket_listen($sock, 5)) < 0) { 
    echo "监听失败原因 " . socket_strerror($ret) . "\n"; 
} 
do { 
  //接收命令  
  if (($msgsock = @socket_accept($sock)) < 0) { 
    echo "命令接收失败原因: " . socket_strerror($msgsock) . "\n"; 
    break; 
  } 
  $msg = "\nphp test server. \n" ."用quit,shutdown,sun...等命令测试.\n"; 
 
  @socket_write($msgsock, $msg, strlen($msg)); 
 
  do { 
    if (false === ($buf = @socket_read($msgsock, 2048, php_normal_read))) { 
        echo "socket_read() failed: reason: " . socket_strerror($ret) . "\n"; 
        break 2; 
    } 
    if (!$buf = trim($buf)) { 
        continue; 
    } 
    if ($buf == 'quit') { 
        break; 
    } 
    if ($buf == 'shutdown') { 
        socket_close($msgsock); 
        break 2; 
    } 
    if ($buf == 'sun') { 
        echo'what are you doing?'; 
    } 
    $talkback = "backinformation : '$buf'.\n"; 
    socket_write($msgsock, $talkback, strlen($talkback)); 
    echo "$buf\n"; 
  } while (true); 
 
  socket_close($msgsock); 
 
} while (true); 
 
socket_close($sock); 
?> 

二、client.php客户端:

<?php 
error_reporting(e_all); 
//端口111 
$service_port = 111; 
//本地 
$address = 'localhost'; 
//创建 tcp/ip socket 
$socket = socket_create(af_inet, sock_stream, sol_tcp); 
if ($socket < 0) { 
    echo "socket创建失败原因: " . socket_strerror($socket) . "\n"; 
} else { 
    echo "ok,he he.\n"; 
} 
$result = socket_connect($socket, $address, $service_port); 
if ($result < 0) { 
    echo "socket连接失败原因: ($result) " . socket_strerror($result) . "\n"; 
} else { 
    echo "ok.\n"; 
} 
//发送命令 
$in = "head / http/1.1\r\n"; 
$in .= "connection: close\r\n\r\n"; 
$out = ''; 
echo "send command.........."; 
$in = "sun\n"; 
socket_write($socket, $in, strlen($in)); 
echo "ok.\n"; 
echo "reading backinformatin:\n\n"; 
while ($out = socket_read($socket, 2048)) { 
    echo $out; 
} 
echo "close socket........"; 
socket_close($socket); 
echo "ok,he he.\n\n"; 
?> 

这两段代码是简单介绍用php实现客户端和服务端的通信

具体操作,在dos下用php命令打开server,处于监听状态..

再打开一个dos窗口,用php命令打开client,会得到服务端的回应....

用PHP的socket实现客户端到服务端的通信实例详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。