首页  >  文章  >  后端开发  >  php socket通信(tcp/udp)实例分析

php socket通信(tcp/udp)实例分析

PHPz
PHPz原创
2016-05-16 19:58:282094浏览

这篇文章主要介绍了php socket通信(tcp/udp)方法,结合实例形式分析了基于socket实现tcp与udp通信的相关技巧,需要的朋友可以参考下。

注意

1.在socket_bind的时候ip地址不能真回环地址如127.0.0.1
2.server.php后台跑起来的时候nohup php server.php > /var/tmp/a.log 2>&1 &

一: udp 方式

1) server.php

<?php
//error_reporting( E_ALL );
set_time_limit( 0 );
ob_implicit_flush();
$socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
if ( $socket === false ) {
  echo "socket_create() failed:reason:" . socket_strerror( socket_last_error() ) . "\n";
}
$ok = socket_bind( $socket, &#39;202.85.218.133&#39;, 11109 );
if ( $ok === false ) {
  echo "socket_bind() failed:reason:" . socket_strerror( socket_last_error( $socket ) );
}
while ( true ) {
  $from = "";
  $port = 0;
  socket_recvfrom( $socket, $buf,1024, 0, $from, $port );
  echo $buf;
  usleep( 1000 );
}
?>

2) client.php

<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$msg = &#39;hello&#39;;
$len = strlen($msg);
socket_sendto($sock, $msg, $len, 0, &#39;202.85.218.133&#39;, 11109);
socket_close($sock);
?>

二: TCP 方式

1)server.php

<?php
//error_reporting( E_ALL );
set_time_limit( 0 );
ob_implicit_flush();
$socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
socket_bind( $socket, &#39;192.168.2.143&#39;, 11109 );
socket_listen($socket);
$acpt=socket_accept($socket);
echo "Acpt!\n";
while ( $acpt ) {
  $words=fgets(STDIN);
  socket_write($acpt,$words);
  $hear=socket_read($acpt,1024);
  echo $hear;
  if("bye\r\n"==$hear){
    socket_shutdown($acpt);
    break;
  }
  usleep( 1000 );
}
socket_close($socket)
?>

2) client.php

<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$con=socket_connect($socket,&#39;192.168.2.143&#39;,11109);
if(!$con){socket_close($socket);exit;}
echo "Link\n";
while($con){
    $hear=socket_read($socket,1024);
    echo $hear;
    $words=fgets(STDIN);
    socket_write($socket,$words);
    if($words=="bye\r\n"){break;}
}
socket_shutdown($socket);
socket_close($sock);
?>

更多相关教程请访问 php编程从入门到精通全套视频教程

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn