服務端代碼
<?php
//確定在連接配接用戶端時不會逾時
set_time_limit(0);
$ip = '127.0.0.1';
$port = 13370;
function doEncoding($str){
$encode = strtoupper(mb_detect_encoding($str, ["ASCII",'UTF-8',"GB2312","GBK",'BIG5']));
if($encode!='UTF-8'){
$str = mb_convert_encoding($str, 'UTF-8', $encode);
}
return $str;
}
/*
+-------------------------------
* @socket通信整個過程
+-------------------------------
* @socket_create
* @socket_bind
* @socket_listen
* @socket_accept
* @socket_read
* @socket_write
* @socket_close
+--------------------------------
*/
/*---------------- 以下操作都是手冊上的 -------------------*/
if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) < 0) {
echo "socket_create() 失敗的原因是:".doEncoding(socket_strerror($sock))."\n";
}
if(($ret = socket_bind($sock,$ip,$port)) < 0) {
echo "socket_bind() 失敗的原因是:".doEncoding(socket_strerror($ret))."\n";
}
if(($ret = socket_listen($sock,4)) < 0) {
echo "socket_listen() 失敗的原因是:".doEncoding(socket_strerror($ret))."\n";
}
$count = 0;
do {
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() failed: reason: " . doEncoding(socket_strerror($msgsock)) . "\n";
break;
} else {
echo "連接配接成功了\n";
//發到用戶端
$msg ="test\n";
socket_write($msgsock, $msg, strlen($msg));
echo "發送資料成功\n";
$buf = socket_read($msgsock,8192);
$talkback = "收到的資訊:$buf\n";
echo $talkback;
}
//echo $buf;
socket_close($msgsock);
} while (true);
socket_close($sock);
echo "連接配接關閉了!\n"
?>
用戶端代碼
<?php
error_reporting(E_ALL);
set_time_limit(0);
echo "<h2>TCP/IP Connection</h2>\n";
$port = 13370;
$ip = "127.0.0.1";
function doEncoding($str){
$encode = strtoupper(mb_detect_encoding($str, ["ASCII",'UTF-8',"GB2312","GBK",'BIG5']));
if($encode!='UTF-8'){
$str = mb_convert_encoding($str, 'UTF-8', $encode);
}
return $str;
}
/*
+-------------------------------
* @socket連接配接整個過程
+-------------------------------
* @socket_create
* @socket_connect
* @socket_write
* @socket_read
* @socket_close
+--------------------------------
*/
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
echo "socket_create() failed: reason: " . doEncoding(socket_strerror($socket)) . "\n";
}else {
echo "OK.\n";
}
echo "試圖連接配接 '$ip' 端口 '$port'...\n";
$result = socket_connect($socket, $ip, $port);
if ($result < 0) {
echo "socket_connect() failed.\nReason: ($result) " . doEncoding(socket_strerror($result)) . "\n";
}else {
echo "連接配接OK\n";
}
$in = "Ho\r\n";
$in .= "first blood\r\n";
$out = '';
if(!socket_write($socket, $in, strlen($in))) {
echo "socket_write() failed: reason: " . doEncoding(socket_strerror($socket)) . "\n";
}else {
echo "發送到伺服器資訊成功!\n";
echo "發送的内容為:<font color='red'>$in</font> <br>";
}
while($out = socket_read($socket, 8192)) {
echo "接收伺服器回傳資訊成功!\n";
echo "接受的内容為:",$out;
}
echo "關閉SOCKET...\n";
socket_close($socket);
echo "關閉OK\n";
?>