首先查看phpinfo()是否开启了socket。
代码方面包括一个server端和一个客户端:
1、server端(server.php)
-
<?php
-
error_reporting(E_ALL & ~E_NOTICE);
-
set_time_limit(0);
-
//ob_implicit_flush();
-
-
$address = '127.0.0.1';
-
$port = 10005;
-
//创建端口
-
if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
-
echo "socket_create() failed :reason:" . socket_strerror(socket_last_error()) . "\n";
-
}
-
-
//绑定
-
if (socket_bind($sock, $address, $port) === false) {
-
echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
-
}
-
-
//监听
-
if (socket_listen($sock, 5) === false) {
-
echo "socket_listen() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
-
}
-
-
do {
-
//得到一个链接
-
if (($msgsock = socket_accept($sock)) === false) {
-
echo "socket_accept() failed :reason:".socket_strerror(socket_last_error($sock)) . "\n";
-
break;
-
}
-
$sendmessage = socket_read($msgsock, 8192);
-
echo "message : <$sendmessage> from client\n";
-
-
-
$msg = "welcome to socket server";
-
socket_write($msgsock, $msg, strlen($msg));
-
socket_close($msgsock);
-
} while(true);
-
//关闭socket
-
socket_close($sock)
2、客户端(client.php)
-
<?php
-
//error_reporting(E_ALL);
-
$service_port = 10005;
-
$address = '127.0.0.1';
-
-
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
-
if ($socket === false) {
-
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
-
}
-
$result = socket_connect($socket, $address, $service_port);
-
if($result === false) {
-
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
-
}
-
$in = "hello socket server";
-
socket_write($socket, $in, strlen($in));
-
-
echo "Reading response:\n";
-
while ($out = socket_read($socket, 8192)) {
-
echo $out."\n";
-
}
-
socket_close($socket)
在服务端用cli方式执行。然后执行客户端,就可以进行socket交互了。
要是服务器间请求,注意下端口是否开启,服务器间网络是否畅通。
阅读(909) | 评论(0) | 转发(0) |