php socket 客户端/服务器端的简单示例

前端之家收集整理的这篇文章主要介绍了php socket 客户端/服务器端的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对简单的PHP socket 客户端/服务器端编程感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

<?PHP
/**
 * 简单的PHP socket 客户端/服务器端编程
 *
 * @param 
 * @arrange 网: jb51.cc
 **/
 error_reporting(E_ALL);
 set_time_limit(0);
 echo "<h2>TCP/IP Connection</h2>\n";
 $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 "连接OK\n";
 }
 $in = "Ho\r\n";
 $in .= "first blood\r\n";
 $out = '';
 if(!socket_write($socket,$in,strlen($in))) {
	 echo "socket_write() Failed: reason: " . socket_strerror($socket) . "\n";
 }else {
	 echo "发送到服务器信息成功!\n";
	 echo "发送的内容为:<font color='red'>$in</font> <br>";
 }
 while($out = socket_read($socket,8192)) {
	 echo "接收服务器回传信息成功!\n";
	 echo "接受的内容为:",$out;
 }
 echo "关闭SOCKET...\n";
 socket_close($socket);
 echo "关闭OK\n";

/***   来自编程之家 jb51.cc(jb51.cc)   ***/

猜你在找的PHP相关文章