SERVER.PHP
代碼
" ;} // 綁定到socket連接埠 if (( $ret = socket_bind( $sock , $address , $port )) < 0 ){ echo " socket_bind() 失敗的原因是: " . socket_strerror( $ret ) . "
" ;} // 開始監聽 if (( $ret = socket_listen( $sock , 4 )) < 0 ){ echo " socket_listen() 失敗的原因是: " . socket_strerror( $ret ) . "
" ;} do { if (( $msgsock = socket_accept( $sock )) < 0 ) { echo " socket_accept() failed: reason: " . socket_strerror( $msgsock ) . " \n " ; break ; } // 發到用戶端 $msg = " 伺服器端發送:歡迎進入伺服器!
" ; socket_write( $msgsock , $msg , strlen ( $msg )); echo " 讀取用戶端發來的資訊
" ; $buf = socket_read( $msgsock , 8192 ); $talkback = " 收到的資訊 $buf
" ; echo $talkback ; if (socket_write( $msgsock , $talkback , strlen ( $talkback )) < 0 ) { echo " socket_write() failed: reason: " . socket_strerror( $msgsock ) . " \n " ; } else { echo " 發送成功 " ; } echo $buf ; socket_close( $msgsock ); } while ( true ); socket_close( $sock ); ?>
CLIENT.PHP
代碼
TCP/IP Connection\n " ; $service_port = 伺服器連接埠; $address = " 伺服器IP " ; $socket = socket_create(AF_INET , SOCK_STREAM , SOL_TCP); if ( $socket < 0 ){ echo " socket_create() failed: reason: " . socket_strerror( $socket ) . " \n " ;} else { echo " OK.\n " ;} echo " 試圖串連 ' $address ' 連接埠 ' $service_port '...
" ; $result = socket_connect( $socket , $address , $service_port ); if ( $result < 0 ) { echo " socket_connect() failed.\nReason: ( $result ) " . socket_strerror( $result ) . " \n " ; } else { echo " 串連OK
" ; } $in = " 發送到伺服器的資訊\r\n " ; $in .= " 也是發到伺服器的\r\n " ; $out = '' ; $out1 = '' ; if ( ! socket_write( $socket , $in , strlen ( $in ))) { echo " socket_write() failed: reason: " . socket_strerror( $socket ) . " \n " ; } else { echo " 發送到伺服器資訊成功!
" ; } while ( $out = socket_read( $socket , 8192 )) { echo " 接收伺服器回傳資訊成功!
" ; echo $out ; } echo " 關閉SOCKET...
" ; socket_close( $socket ); echo " 關閉OK
" ; ?>