server:
1 php 2set_time_limit(0); 3 4$ip = '127.0.0.1'; 5$port = 8888; 6 7// 1. 创建 8if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == FALSE ){ 9echo 'create fail:' . socket_strerror(socket_last_error()); 10} 1112// 2. 绑定13if ( socket_bind($sock, $ip, $port) == FALSE ) { 14echo 'bind fail:' . socket_strerror(socket_last_error()); 15} 1617// 3. 监听18if( socket_listen($sock, 4) == FALSE ){ 19echo 'listen fail:' . socket_strerror(socket_last_error()); 20} 2122$count = 0; 2324do{ 25// 4. 阻塞,等待客户端请求26if ( ($msgsock = socket_accept($sock)) == FALSE ) { 2728echo 'accept fail:' . socket_strerror(socket_last_error()); 2930break; 31 } else { 3233// 5. 向客户端写入信息34$msg = 'server send successfully!'; 35 socket_write($msgsock, $msg, strlen($msg)); 363738// 5. 读取客户端信息39echo '-----test successfully!------'; 40$buf = socket_read($msgsock, 8192); 414243$talkback = 'receive client: ' . $buf; 44echo$talkback; 454647if ($count >= 5) { 48break; 49 } 50 } 5152// 6. 关闭socket53 socket_close($msgsock); 5455 }while(true); 5657// 6. 关闭socket58 socket_close($sock);
client:
php error_reporting(E_ALL); set_time_limit(0); $ip = '127.0.0.1'; $port = 8888; // 1. 创建$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if( $socket == FALSE ) { echo 'create fail: ' . socket_strerror(socket_last_error()); } else { echo 'OK'; } // 2. 链接echo 'we will try to connect ' . $ip .':' . $port . '\r\n----'; $result = socket_connect($socket, $ip, $port); if ( $result == FALSE) { } $in = 'HO '; $in .= 'first blood--------'; $out = ''; // 3. 向服务端写入if( !socket_write($socket, $in, strlen($in)) ) { echo 'write fail: ' . socket_strerror(socket_last_error()); } else { echo '-----send to server succefully! \r\n----'; echo 'the content is ' . $in; } // 3. 从服务端读取while ( $out = socket_read($socket, 8129) ) { echo '-----receive from server succefully!\r\n------'; echo 'the contents is ' . $out; } // 4. 关闭echo '----close socket ...'; socket_close($socket); echo 'closed ok.';
以上就介绍了phpsocket 简单的php socket 实例,包括了phpsocket方面的内容,希望对PHP教程有兴趣的朋友有所帮助。
已抢111605个
抢已抢47427个
抢已抢134001个
抢已抢32530个
抢已抢562个
抢已抢1087个
抢