PHP SOCKET編程!

來源:互聯網
上載者:User
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
" ; ?>

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.