最近好奇,接触接触PHP的socket编程,发现还是很好玩儿的。下面贴出来demo源码跟大家分享
Server.php
<?php /** * PHP Socket Server * */ //确保客户端连接时不会超时 error_reporting(0); set_time_limit(0); //设置地址与端口 $address = '127.0.0.1'; //服务端ip $port = 2046; //创建socket:AF_INET=是ipv4 如果用ipv6,则参数为 AF_INET6 , SOCK_STREAM为socket的tcp类型,如果是UDP则使用SOCK_DGRAM $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() failed : ".socket_strerror(socket_last_error()). "\n"); //阻塞模式 socket_set_block($sock) or die("socket_set_block() failed : ".socket_strerror(socket_last_error()) ."\n"); //绑定到socket端口 $result = socket_bind($sock, $address, $port) or die("socket_bind() failed : ". socket_strerror(socket_last_error()) . "\n"); //开始监听 $result = socket_listen($sock, 4) or die("socket_listen() failed : ". socket_strerror(socket_last_error()) . "\n"); echo "OK\nBinding the socket on $address:$port ...\n"; echo "OK\nNow ready to accept connections.\nListening on the socket ...\n"; do {//Never stop the daemon //它接收连接请求并调用一个子链接socket来处理客户端和服务器间的信息 $msgsock = socket_accept($sock) or die("sock_accept() failed : ". socket_strerror(socket_last_error()) . "\n"); //读取客户端数据 echo "Read client data \n"; $buf = socket_read($msgsock, 8192); echo "Received msg : $buf \n"; //数据传输,向客户端写入返回结果 $msg = "welcome \n"; socket_write($msgsock, $msg, strlen($msg)) or die("socket_write() failed : ". socket_strerror(socket_last_error()). "\n"); //输出返回到客户端时,父/子socket都应通过socket_close来终止 socket_close($msgsock); }while(true); socket_close($sock);
Client.php
<?php /** * php socket client * */ error_reporting(0); set_time_limit(0); $host = '127.0.0.1'; $port = 2046; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket.\n"); $connection = socket_connect($socket, $host, $port) or die("Could not connect server.\n"); socket_write($socket, "Hello Socket!") or die("Write failed.\n"); while($buff = socket_read($socket, 1024, PHP_NORMAL_READ)) { echo "Response was : ". $buff . "\n"; } socket_close($socket);