Linux教程網
mini2440上Apache php的socket通信
server.php
[php]
- <?php
- //確保在連接客戶端時不會超時
- set_time_limit(0);
-
- //設置IP和端口號
- $address='127.0.0.1';
- $port=2009; //調試的時候,可以多換端口來測試程序!
-
- //創建一個SOCKET
- if(($sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP))<0)
- {
- echo "socket_create() 失敗的原因是:".socket_strerror($sock)."<br>";
- }
-
- //綁定到socket端口
- if(($ret=socket_bind($sock,$address,$port))<0)
- {
- echo "socket_bind() 失敗的原因是:".socket_strerror($ret)."\n";
- }
-
- //開始監聽
- if(($ret=socket_listen($sock,4))<0)
- {
- echo "socket_listen() 失敗的原因是:".socket_strerror($ret)."\n";
- }
-
- do {
- if (($msgsock = socket_accept($sock)) < 0)
- {
- echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
- break;
- }
- //發到客戶端
- $msg ="<font color=red>歡迎進入服務器!</font><br>";
- socket_write($msgsock, $msg, strlen($msg));
-
- echo "讀取客戶端發來的信息<br>";
- $buf = socket_read($msgsock,8192);
-
-
- $talkback = "收到的信息:$buf<br>";
- 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
[php]
- <?php
- error_reporting(E_ALL);
- set_time_limit(0);
- echo "<h2>TCP/IP Connection</h2>\n";
-
- $service_port = 2009;
- $address = "127.0.0.1";
-
- $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 ...<br>";
- $result = socket_connect($socket, $address, $service_port);
- if ($result < 0)
- {
- echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
- }
- else
- {
- echo "連接OK<br>";
- }
-
- $in = "Hello\r\n";
- $in .= "我是Chester\r\n";
- $out = '';
- $out1='';
-
-
- if(!socket_write($socket, $in, strlen($in)))
- {
- echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
- }
- else
- {
- echo "發送到服務器信息成功!<br>";
- echo "發送的內容為:<font color='red'>$in</font> <br>";
- }
-
- while($out = socket_read($socket, 8192))
- {
- echo "接收服務器回傳信息成功!<br>";
- echo "接受的內容為:",$out;
- }
-
- echo "關閉SOCKET...<br>";
- socket_close($socket);
- echo "關閉OK<br>";
- ?>
實驗結果如下:
Copyright ©
Linux教程網 All Rights Reserved