<?php
$protocol = getprotobyname('tcp'); //获取integer
$socket = socket_create(AF_INET, SOCK_STREAM, $protocol);
if ($socket === false) {
echo socket_last_error();
} else {
echo "create socket is ok. use tcp protocol.
";
}
$bind = socket_bind($socket, '127.0.0.1', 1324);
if ($bind === false) {
echo socket_last_error();
} else {
echo "bind address and port successfully.
";
}
$listen = socket_listen($socket);
if ($listen === false) {
echo socket_last_error();
} else {
echo "service is listening...
";
}
// socket_set_nonblock($socket);
do{
$accept = socket_accept($socket);
if (!$accept) {
echo socket_last_error();
} else {
// print_r($accept);
$read = socket_read($accept, 1024); // 经测试:socket_read(),函数第一个参数使用socket_create返回的资源$socket 不行。,读取不到数据,必须使用socket_accept函数返回的资源$accept 才能正常获取到传输的数据
if ($read === false) {
echo socket_last_error();
} else {
echo $read;
$buffer = "
hello i am a server.
";
socket_write($accept, $buffer, strlen($buffer));
// 和客户端交互, 根据客户端输入参数返回不同的数据
while (true) {
$res = socket_read($accept, 1024);
if ($res === false) {
break;
}
echo "
client sended :
", $res;
switch (substr($res, 0, 1)) {
case 'a':
$send_data = 'aaaaaaaaaa';
break;
case 'b':
$send_data = 'bbbbbbbbbb';
break;
case 'c':
$send_data = 'cccccccccc';
break;
default:
$send_data = 'dddddddddd';
break;
}
socket_write($accept, $send_data, strlen($send_data));
}
}
}
// socket_close($socket);
} while (true);
socket_close($socket);