《PHP编程:php socket通信(tcp/udp)实例分析》要点:
本文介绍了PHP编程:php socket通信(tcp/udp)实例分析,希望对您有用。如果有疑问,可以联系我们。
PHP教程本文实例讲述了php socket通信(tcp/udp)办法.分享给大家供大家参考,具体如下:
PHP教程注意
PHP教程1.在socket_bind的时候ip地址不能真回环地址如127.0.0.1
2.server.php后台跑起来的时候nohup php server.php > /var/tmp/a.log 2>&1 &
PHP教程一: udp 方式
PHP教程1) server.php
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, '202.85.218.133', 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 );
}
?>
PHP教程2) client.php
PHP教程
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$msg = 'hello';
$len = strlen($msg);
socket_sendto($sock, $msg, $len, 0, '202.85.218.133', 11109);
socket_close($sock);
?>
PHP教程二: TCP 方式
PHP教程1)server.php
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, '192.168.2.143', 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)
?>
PHP教程2) client.php
PHP教程
<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$con=socket_connect($socket,'192.168.2.143',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教程更多关于PHP相关内容感兴趣的读者可查看本站专题:《php socket用法总结》、《PHP基本语法入门教程》、《PHP错误与异常处理办法总结》及《php常用函数与技巧总结》
PHP教程希望本文所述对大家PHP程序设计有所赞助.
维易PHP培训学院每天发布《PHP编程:php socket通信(tcp/udp)实例分析》等实战技能,PHP、MYSQL、LINUX、APP、JS,CSS全面培养人才。
转载请注明本页网址:
http://www.vephp.com/jiaocheng/7549.html