<?php 
/**
* @file
* @breif UDPクラス
*
* @note 
*
* @date 2005/03/07	新規作成
*
* @author $author$
*
* $Revision$
*/

/// UDPクラス
class UDP
{
	var $_socket_fp	= null;	///< ソケットファイルポインタ

	/**
	* コンストラクタ
	*/
	function UDP()
	{
	}

	/**
	* ソケットオープン
	*
	* @param string	$host	: 接続先ホスト名
	* @param int	$port	: ポート番号
	* @param int	$timeout_seconds : タイムアウト秒数
	* @return bool			: true/false
	*/
	function open($host, $port, $timeout_seconds = 30)
	{
		$this->_socket_fp = fsockopen("udp://$host", $port, $errno, $errstr, $timeout_seconds);
		if(!$this->_socket_fp) return false;
		socket_set_blocking($this->_socket_fp, false);
		return true;
	}

	/**
	* ソケットクローズ
	*/
	function close()
	{
		if($this->_socket_fp){
			fclose($this->_socket_fp);
			$this->_socket_fp = null;
		}
	} 

	/**
	* 最終エラー文字列取得
	*
	* @return string : エラー文字列
	*/
	function getLastError()
	{
		return socket_strerror(socket_last_error());
	}

	/**
	* データ送信
	*
	* @param mixed	&$data	: データ
	* @return int : 成功：書き込んだバイト数 / 失敗：false
	*/
	function send(&$data)
	{
		if(!$this->_socket_fp) return false;
		return fwrite($this->_socket_fp, $data);
	}

	/**
	* データ受信
	*
	* @param mixed	&$data	: データ
	* @param int	$timeout_seconds : タイムアウト秒数
	* @return mixed $data : 成功：読み込んだ内容 / 失敗：false
	*/
	function receive(&$data, $timeout_seconds = 1)
	{
		if(!$this->_socket_fp) return false;
		$data = '';
		$newData = '';
		do {
			$currentTime = time();
			$data .= $newData;
			$newData = fread($this->_socket_fp, 1024);
			if (($newData != '') || (isset($timeoutTime) == false)) {
				$timeoutTime = $currentTime + $timeout_seconds;
			} 
		} while ((($newData != '') || ($data == '')) && ($currentTime < $timeoutTime));
		return $data;
	}
} 

?>
