#TCP示例

 

//服务端
<?php

//创建socket套接字
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//设置阻塞模式
socket_set_block($socket);
//为套接字绑定ip和端口
socket_bind($socket,'127.0.0.1',3046);
//监听socket
socket_listen($socket,4);

while(true)
{
//接收客户端请求
if(($msgsocket = socket_accept($socket)) !== false)
{
//读取请求内容
$buf = socket_read($msgsocket, 8192);
echo "$buf \n";
$str = '{"code":200}';
//向连接的客户端发送数据
socket_write($msgsocket, $str,strlen($str));
//操作完之后需要关闭该连接否则 feof() 函数无法正确识别打开的句柄是否读取完成
socket_close($msgsocket);
}
}



//客户端
<?php
$st = "send something";
echo $st."\r\n";
//创建tcp套接字
$i=1;
while(true){
echo $i."\r\n";
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
$length = strlen($st);
//连接tcp
socket_connect($socket, '127.0.0.1',3046);
//向打开的套集字写入数据(发送数据)
$s = socket_write($socket, $st, $length);
//从套接字中获取服务器发送来的数据
$msg = socket_read($socket,8190);
//关闭连接
sleep(1);
socket_close($socket);
$i++;
}


#UPD示例



//服务端
private function udpServer(){
//服务器信息
$server = 'udp://127.0.0.1:9998';
//消息结束符号
$msg_eof = "\n";
$socket = stream_socket_server($server, $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
die("$errstr ($errno)");
}

do {
//接收客户端发来的信息
$inMsg = stream_socket_recvfrom($socket, 1024, 0, $peer);
//服务端打印出相关信息
echo "Client : $peer\n";
echo "Receive : {$inMsg}";
//给客户端发送信息
$outMsg = substr($inMsg, 0, (strrpos($inMsg, $msg_eof))).' -- '.date("D M j H:i:s Y\r\n");
stream_socket_sendto($socket, $outMsg, 0, $peer);

} while ($inMsg !== false);
}

//客户端
private function udpClient(){
$udpGet = function ($sendMsg = '', $ip = '127.0.0.1', $port = '9998'){
$handle = stream_socket_client("udp://{$ip}:{$port}", $errno, $errstr);
if( !$handle ){
die("ERROR: {$errno} - {$errstr}\n");
}
fwrite($handle, $sendMsg."\n");
$result = fread($handle, 1024);
fclose($handle);
return $result;
};

$result = $udpGet('Hello World');
echo $result;
}


posted on 2020-08-21 15:00  cyqAkin  阅读(179)  评论(0编辑  收藏  举报