PHP?也可以使用socket,先開啟socket擴(kuò)展。
/**
?*File name server.php
?*服務(wù)器端代碼
?*/???
//確保在連接客戶端時不會超時?
set_time_limit(0);?
//設(shè)置IP和端口號?
$address = "127.0.0.1";?
$port = 2046; //調(diào)試的時候寒锚,可以多換端口來測試程序忽匈!?
/**
?*創(chuàng)建一個SOCKET?
?*AF_INET=是ipv4? ? 如果用ipv6他嚷,則參數(shù)為AF_INET6
?*SOCK_STREAM為socket的tcp類型坤溃,如果是UDP則使用SOCK_DGRAM
*/?
$sock = socket_create(AF_INET, SOCK_STREAM,
SOL_TCP) or die("socket_create() 失敗的原因是:" . socket_strerror(socket_last_error()) ."/n");?
//阻塞模式?
socket_set_block($sock) or
die("socket_set_block() 失敗的原因是:" . socket_strerror(socket_last_error()) ."/n");?
//綁定到socket端口?
$result = socket_bind($sock, $address,
$port) or die("socket_bind() 失敗的原因是:" . socket_strerror(socket_last_error()) ."/n");?
//開始監(jiān)聽?
$result = socket_listen($sock, 4) or
die("socket_listen() 失敗的原因是:" . socket_strerror(socket_last_error()) ."/n");?
echo "OK\nBinding the socket on$address:$port ... ";?
echo "OK\nNow ready to accept connections.\nListeningon the socket ... \n";?
do { // never stop the daemon?
???//它接收連接請求并調(diào)用一個子連接Socket來處理客戶端和服務(wù)器間的信息?
???$msgsock = socket_accept($sock) or?die("socket_accept() failed: reason: " .socket_strerror(socket_last_error()) . "/n");???????
? ??//讀取客戶端數(shù)據(jù)?
???echo "Read client data \n";?
???//socket_read函數(shù)會一直讀取客戶端數(shù)據(jù),直到遇見\n,\t或者\0字符.PHP腳本把這寫字符看做是輸入的結(jié)束符.?
???$buf = socket_read($msgsock, 8192);?
???echo "Received msg: $buf??\n";???????
???//數(shù)據(jù)傳送向客戶端寫入返回結(jié)果?
???$msg = "welcome \n";?
? ??socket_write($msgsock, $msg, strlen($msg)) ordie("socket_write() failed: reason: " .socket_strerror(socket_last_error()) ."/n");?
???//一旦輸出被返回到客戶端,父/子socket都應(yīng)通過socket_close($msgsock)函數(shù)來終止?
???socket_close($msgsock);?
} while (true);?
socket_close($sock);
/**
?*File name:client.php
?*客戶端代碼
?*?
?*@author guisu.huang
?*@since 2012-04-11
?*/?
set_time_limit(0);?
$host = "120.55.81.171";?
$port = 7000;?
$socket = socket_create(AF_INET,SOCK_STREAM, SOL_TCP)or die("Could not create? socket\n"); //創(chuàng)建一個Socket?
$connection = socket_connect($socket,$host, $port) or die("Could not connet server\n");??? //? 連接?
socket_write($socket,
"SOS@@123456789012345@@1@@11403.6791@@2240.5644@@201701041319") or
die("Write failed\n"); // 數(shù)據(jù)傳送向服務(wù)器發(fā)送消息?
while ($buff = socket_read($socket, 1024,PHP_NORMAL_READ)) {?
???echo("Response was:" . $buff . "\n");?
}?
socket_close($socket);
實測
PHP服務(wù)端腳本
一旦連接發(fā)送消息成功后,立馬斷開連接昧互。