php cocket的使用方法

來源:互聯網
上載者:User
這篇文章主要介紹了關於php cocket的使用方法,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

window下,開啟命令視窗,分別運行以下兩行命令:

# php.exe e:/wwwroot/server.php# php.exe e:/wwwroot/server.php

以下代碼來自php官方手冊

server.php:

<?php //The Server error_reporting(E_ALL); $address = "127.0.0.1"; $port = "10000";   /* create a socket in the AF_INET family, using SOCK_STREAM for TCP connection */ $mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($mysock, $address, $port); socket_listen($mysock, 5); $client = socket_accept($mysock); echo "Server started, accepting connections...\n";   $i = 0; while (true == true) {     $i++;     echo "Sending $i to client.\n";     socket_write($client, $i, strlen($i));         $input = socket_read($client, 2048);     echo "Response from client is: $input\n";     sleep(5); } echo "Closing sockets..."; socket_close($client); socket_close($mysock);

client.php

<?php //The Client error_reporting(E_ALL); $address = "127.0.0.1"; $port = 10000; /* Create a TCP/IP socket. */ $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) {     echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; } else {     echo "socket successfully created.\n"; } echo "Attempting to connect to '$address' on port '$port'..."; $result = socket_connect($socket, $address, $port); if ($result === false) {     echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n"; } else {     echo "successfully connected to $address.\n"; } $i = 0; while (true == true) {     $i++;     echo "Sending $i to server.\n";     socket_write($socket, $i, strlen($i));         $input = socket_read($socket, 2048);     echo "Response from server is: $input\n";     sleep(5); } echo "Closing socket..."; socket_close($socket);

以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.