简单的php socket 实例

server:

 1 <?php
 2 set_time_limit(0);
 3 
 4 $ip = '127.0.0.1';
 5 $port = 8888;
 6 
 7 // 1. 创建
 8 if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) == FALSE ){
 9     echo 'create fail:' . socket_strerror(socket_last_error());
10 }
11 
12 // 2. 绑定
13 if ( socket_bind($sock, $ip, $port) == FALSE ) {
14     echo 'bind fail:' . socket_strerror(socket_last_error());
15 }
16 
17 // 3. 监听
18 if( socket_listen($sock, 4) == FALSE ){
19     echo 'listen fail:' . socket_strerror(socket_last_error());
20 }
21 
22 $count = 0;
23 
24 do{
25     // 4. 阻塞,等待客户端请求
26     if ( ($msgsock = socket_accept($sock)) == FALSE ) {
27         
28         echo 'accept fail:' . socket_strerror(socket_last_error());
29         
30         break;
31     } else {
32 
33         // 5. 向客户端写入信息
34         $msg = 'server send successfully!';
35         socket_write($msgsock, $msg, strlen($msg));
36 
37         
38         // 5. 读取客户端信息
39         echo '-----test successfully!------';
40         $buf = socket_read($msgsock, 8192);
41 
42 
43         $talkback = 'receive client: ' . $buf;
44         echo $talkback;
45 
46 
47         if ($count >= 5) {
48             break;
49         }
50     }
51 
52     // 6. 关闭socket
53     socket_close($msgsock);
54 
55 }while(true);
56 
57 // 6. 关闭socket
58 socket_close($sock);

 

 

client:

<?php
error_reporting(E_ALL);
set_time_limit(0);


$ip = '127.0.0.1';
$port = 8888;

// 1. 创建
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if( $socket == FALSE ) {
    echo 'create fail: ' . socket_strerror(socket_last_error());
} else {
    echo 'OK';
}

// 2. 链接
echo 'we will try to connect ' . $ip .':' . $port . '\r\n----';
$result = socket_connect($socket, $ip, $port);
if ( $result == FALSE) {
    
}

$in = 'HO ';
$in .= 'first blood--------';
$out = '';

// 3. 向服务端写入
if( !socket_write($socket, $in, strlen($in)) ) {
    echo 'write fail: ' . socket_strerror(socket_last_error());
} else {
    echo '-----send to server succefully! \r\n----';
    echo 'the content is ' . $in;
}

// 3. 从服务端读取
while ( $out = socket_read($socket, 8129) ) {
    echo '-----receive from server succefully!\r\n------';
    echo 'the contents is ' . $out;
}

// 4. 关闭
echo '----close socket ...';
socket_close($socket);
echo 'closed ok.';

 

 

 

posted @ 2016-07-26 16:17  kravis  阅读(6123)  评论(5编辑  收藏  举报