Skip to content

Instantly share code, notes, and snippets.

@ninehills
Created August 9, 2010 06:08
Show Gist options
  • Save ninehills/515025 to your computer and use it in GitHub Desktop.
Save ninehills/515025 to your computer and use it in GitHub Desktop.
php socket server
<?php
require("sql.php");
//确保在连接客户端时不会超时
set_time_limit(0);
//设置IP和端口号
$address = 'localhost';
$port = 2009;
//创建一个TCP Stream Socket
if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) === false)
{
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
//绑定到socket端口
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 {
// accept any connections coming in on this socket
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
/* Send instructions. */
$msg ="\nWelcome to GPS Data Server. \n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
do{
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
break;
}
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
$talkback = "Message is '$buf'.\n";
socket_write($msgsock, $talkback, strlen($talkback));
echo "Receive Message is $buf\n";
//写入接收到的数据到数据库中
$data = explode(",",$buf);
if(count($data) == 4){
db_connect();
$Number = intval($data[0]);
$Longitude = floatval($data[1]);
$Latitude = floatval($data[2]);
$UTCTime = $data[3];
$sql = "insert into geodata(number, longitude, latitude, utctime) values
('".$Number."', '".$Longitude."', '".$Latitude."', '".$UTCTime."')";
$result = mysql_query($sql);
if ($result){
echo "Data Save Success. \n";
} else {
echo "There's been a problem: ".mysql_error() ."\n";
}
mysql_close();
} else {
echo "Data is NOT Valid \n";
}
} while (true);
socket_close($msgsock);
} while (true);
socket_close($sock);
?>
@IshikawaHideki
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment