这里仅记录tcp协议:
关于server:
<?php /** * 测试关于php的socket函数 */ /** * 最基本的socket,服务器端: * 创建 * $sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); * 绑定 * socket_bind($sock,‘127.0.0.1‘); * 监听 * socket_listen($sock,5); * 得到连接 * $msgSock = socket_accept($sock); * socket_write(); * socket_read(); */ $address = ‘127.0.0.1‘; $port = 12345; if(($sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname(‘tcp‘)))===false) { echo "socket create failed ".socket_strerror(socket_last_error())."\r\n"; } //绑定 if(socket_bind($sock,$address,$port) === false) { echo ‘socket bind failed ‘.socket_strerror(socket_last_error())."\r\n"; } //监听 if(socket_listen($sock,10) === false) { echo ‘socket listen failed ‘.socket_strerror(socket_last_error())."\r\n"; } do { $msgSock = socket_accept($sock); if($msgSock === false) { echo ‘socket accept failed ‘.socket_strerror(socket_last_error())."\r\n"; break; } //发送到客户端 $msg = "server连接成功了!\r\n"; socket_write($msgSock,$msg,strlen($msg)); //读从客户端接收的数据 $reciveMsg = socket_read($msgSock,8192); echo "reciveed msg is: ".$reciveMsg."\r\n"; socket_close($msgSock); }while(true); socket_close($sock);
关于client:
<?php /** * 关于客户端的socket */ /** * 函数 * socket_create(); * socket_connect(); * socket_write(); * socket_read(); */ $address = ‘127.0.0.1‘; $port = 12345; $sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); if($sock === false) { echo "socket create failed ".socket_strerror(socket_last_error())."\r\n"; } echo "attempt to connect server...\r\n"; $result = socket_connect($sock,$address,$port); if($result === false) { echo "socket connect failed ".socket_strerror(socket_last_error())."\r\n"; } echo ‘connect to server ..‘."\r\n"; $msg = "client connect success\r\n"; socket_write($sock,$msg,strlen($msg)); while($out = socket_read($sock,8192)) { echo $out."\r\n"; } echo "close socket ..\r\n"; socket_close($sock);
php的socket还有一种套接字流,都是stream打头的函数,其中也有server和client,这里不记录
原文:http://www.cnblogs.com/phpzhou/p/5518291.html