01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?php set_time_limit(0); $host = "localhost" ; $port =1001; //創建一個連接 $socket =socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or
die ( "cannot create socket\n" ); //綁定socket到端口 $result =socket_bind( $socket , $host , $port )
or
die ( "cannot bind port to socket\n" ); //開始監聽這個端口 $result =socket_listen( $socket ,4)
or
die ( "could not set up socket listen\n" ); //接受連接,另一個socket來處理通信 $msgsock =socket_accept( $socket )
or
die ( "cannot accept incoming connection\n" ); if ( $msgsock ){ echo
date ( "Y-m-d H:i:s D a" ); } //讀取客戶端發送過來的信息 $input =socket_read( $msgsock ,1024)
or
die ( "cannot read input\n" ); $input =trim( $input ); $output = strrev ( $input ). "順序反過來了吧\n" ; //對接收到的信息進行處理,然後返回到客戶端 socket_write( $msgsock , $output , strlen ( $output ))
or
die ( "cannot write" ); //關閉socket連接 socket_close( $msgsock ); socket_close( $socket ); ?> |
客戶端
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
|
<?php set_time_limit(0); $host = "localhost" ; $port =1001; //創建一個socket $socket =socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or
die ( "cannot create socket\n" ); $conn =socket_connect( $socket , $host , $port )
or
die ( "cannot connect server\n" ); if ( $conn ){ echo
"client connect ok!" ;} socket_write( $socket , "hello
world!" ) or
die ( "cannot write data\n" ); $buffer =socket_read( $socket ,1024,PHP_NORMAL_READ); if ( $buffer ){ echo
"response was:" . $buffer . "\n" ; }
socket_close( $socket ); ?> |