<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rogério Lino &#187; classe</title>
	<atom:link href="http://rogeriolino.com/tags/classe/feed/" rel="self" type="application/rss+xml" />
	<link>http://rogeriolino.com</link>
	<description>Desenvolvimento Web, tecnologia, jogos e etcetera</description>
	<lastBuildDate>Wed, 01 Feb 2012 19:22:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>PHP: Socket Class</title>
		<link>http://rogeriolino.com/2010/04/22/php-socket-class/</link>
		<comments>http://rogeriolino.com/2010/04/22/php-socket-class/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 19:19:03 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[classe]]></category>
		<category><![CDATA[connection]]></category>
		<category><![CDATA[license]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[tcp]]></category>
		<category><![CDATA[udp]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=284</guid>
		<description><![CDATA[<p>Muitas linguagens oferecem suporte a <a href="http://en.wikipedia.org/wiki/Internet_socket">Sockets</a>, e com <a href="http://php.net/manual/en/book.sockets.php">PHP</a> não é diferente, porém a falta de orientação a objetos nas funções do PHP pode ser um inconveniente para algumas pessoas. E como eu me incluo entre essas pessoas, quando precisei utilizar sockets em PHP acabei criando um classe para englobar essas funções soltas [...]]]></description>
			<content:encoded><![CDATA[<p>Muitas linguagens oferecem suporte a <a href="http://en.wikipedia.org/wiki/Internet_socket">Sockets</a>, e com <a href="http://php.net/manual/en/book.sockets.php">PHP</a> não é diferente, porém a falta de orientação a objetos nas funções do PHP pode ser um inconveniente para algumas pessoas. E como eu me incluo entre essas pessoas, quando precisei utilizar sockets em PHP acabei criando um classe para englobar essas funções soltas e fornecer tratamento a erros.</p>
<pre name="code" class="php">/**
 * Copyright 2010 Rogerio Alencar Lino Filho
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Socket
 *
 * @author rogeriolino
 */
class Socket {

    private $port     = 3000;
    private $address  = "localhost";
    private $blocking = true;

    private $buffer   = 2048;
    private $backlog  = 5;

    private $type     = SOCK_STREAM;
    private $family   = AF_INET;
    private $protocol = SOL_TCP;

    private $resource;

    /**
     * Socket constructor
     * @param  $resource
     */
    public function  __construct($resource = null) {
        if ($resource == null) {
            $this-&gt;resource = socket_create($this-&gt;family, $this-&gt;type, $this-&gt;protocol);
        } else {
            $this-&gt;resource = $resource;
        }
    }

    /**
     * Returns the socket port
     * @return int
     */
    public function get_port() {
        return $this-&gt;port;
    }

    /**
     * Define the socket port
     * @param int $port
     */
    public function set_port($port) {
        $this-&gt;port = $port;
    }

    /**
     *
     * @return string
     */
    public function get_address() {
        return $this-&gt;address;
    }

    public function set_address($address) {
        $this-&gt;address = $address;
    }

    /**
     * Returns if the socket is blocking mode
     * @return boolean
     */
    public function is_blocking() {
        return $this-&gt;blocking;
    }

    /**
     * Defines whether the socket is blocking or nonblocking mode
     * @param boolean $block
     */
    public function set_blocking($blocking) {
        $this-&gt;blocking = ($blocking == true);
        $this-&gt;update_blocking_mode();
    }

    /**
     * Returns the socket communication type
     * @return int
     */
    public function get_type() {
        return $this-&gt;type;
    }

    /**
     * Define the socket communication type
     * @param int $type
     */
    public function set_type($type) {
        if ($type == SOCK_STREAM || $type == SOCK_DGRAM || $type == SOCK_SEQPACKET || $type == SOCK_RAW || $type == SOCK_RDM) {
            $this-&gt;type = $type;
        } else {
            throw new Socket_Exception("Invalid socket communication type");
        }
    }

    /**
     * Returns the socket protocol family
     * @return int
     */
    public function get_family() {
        return $this-&gt;family;
    }

    /**
     * Define the socket protocol family
     * @param int $family
     */
    public function set_family($family) {
        if ($family == AF_INET || $family == AF_INET6 || $family == AF_UNIX) {
            $this-&gt;family = $family;
        } else {
            throw new Socket_Exception("Invalid socket protocol family");
        }
    }

    /**
     * Returns the socket protocol
     * @return int
     */
    public function get_protocol() {
        return $this-&gt;protocol;
    }

    /**
     * Define the socket protocol, must be compatible whit the protocol family
     * @param int $protocol
     */
    public function set_protocol($protocol) {
        if ($protocol == SOL_TCP || $protocol == SOL_UDP || $protocol == SOL_SOCKET) {
            $this-&gt;protocol = $protocol;
        } else {
            throw new Socket_Exception("Invalid socket protocol");
        }
    }

    /**
     * Binds to a socket
     * @throws Socket_Exception
     */
    public function bind() {
        if (socket_bind($this-&gt;resource, $this-&gt;address, $this-&gt;port) === false) {
            throw new Socket_Exception("Socket bind failed: " . $this-&gt;error());
        }
    }

    /**
     * Listens for a connection on a socket
     * @throws Socket_Exception
     */
    public function listen() {
        if (socket_listen($this-&gt;resource, $this-&gt;backlog) === false) {
            throw new Socket_Exception("Socket listen failed: " . $this-&gt;error());
        }
    }

    /**
     * Accepts a connection
     * @throws Socket_Exception
     * @return Socket
     */
    public function accept() {
        $sock = socket_accept($this-&gt;resource);
        if ($sock === false) {
            throw new Socket_Exception("Socket accept failed: " . $this-&gt;error());
        }
        return new Socket($sock);
    }

    /**
     * Reads data from the connected socket
     * @return string
     */
    public function read() {
        $data = "";
        while (($m = socket_read($this-&gt;resource, $this-&gt;buffer)) != "") {
            $data .= $m;
        }
        return $data;
    }

    /**
     * Write the data to connected socket
     * @param string $message
     */
    public function write($data) {
        socket_write($this-&gt;resource, $data, strlen($data));
    }

    /**
     * Initiates a connection on a socket
     * @throws Socket_Exception
     * @return boolean
     */
    public function connect() {
        try {
            return socket_connect($this-&gt;resource, $this-&gt;address, $this-&gt;port);
        } catch (Socket_Exception $e) {
            return false;
        }
    }

    /**
     * Close the socket connection
     */
    public function close() {
        socket_close($this-&gt;resource);
    }

    private function update_blocking_mode() {
        if ($this-&gt;blocking) {
            socket_set_block($this-&gt;resource);
        } else {
            socket_set_nonblock($this-&gt;resource);
        }
    }

    private function error() {
        return socket_strerror(socket_last_error($this-&gt;resource));
    }

}
</pre>
<p>Classe para as exceções:</p>
<pre name="code" class="php">/**
 * Copyright 2010 Rogerio Alencar Lino Filho
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Socket_Exception
 *
 * @author rogeriolino
 */
class Socket_Exception extends Exception {

    public function  __construct($message, $code = 0, $previous = null) {
        $this-&gt;message = $message;
        $this-&gt;code = $code;
        $this-&gt;message = $previous;
    }

}
</pre>
<p>Espero que seja de bom aproveito.</p>
]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2010/04/22/php-socket-class/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Javascript: Classe Math</title>
		<link>http://rogeriolino.com/2007/01/19/javascript-classe-math/</link>
		<comments>http://rogeriolino.com/2007/01/19/javascript-classe-math/#comments</comments>
		<pubDate>Fri, 19 Jan 2007 19:57:38 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[classe]]></category>
		<category><![CDATA[euler]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[max]]></category>
		<category><![CDATA[min]]></category>
		<category><![CDATA[pi]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[round]]></category>
		<category><![CDATA[util]]></category>

		<guid isPermaLink="false">http://rogeriolino.wordpress.com/2007/01/19/javascript-classe-math/</guid>
		<description><![CDATA[<p>Assim como a <a href="http://rogeriolino.wordpress.com/2007/01/11/javascript-classe-date/" title="Classe Data" target="_blank">classe Date()</a> uma outra classe nativa em várias linguagens que quebra um galho legal é a Math (Mathematical).</p> <p>Além de contar com algumas funções ela também fornece valores de constantes ou valores matemáticos, como por exemplo PI e raiz quadrada de 2.</p> <p>Funções:</p> <p>Math.round() : Arredonda um valor [...]]]></description>
			<content:encoded><![CDATA[<p>Assim como a <a href="http://rogeriolino.wordpress.com/2007/01/11/javascript-classe-date/" title="Classe Data" target="_blank">classe Date()</a> uma outra classe nativa em várias linguagens que quebra um galho legal é a Math (Mathematical).</p>
<p>Além de contar com algumas funções ela também fornece valores de constantes ou valores matemáticos, como por exemplo PI e raiz quadrada de 2.</p>
<p><strong>Funções:</strong></p>
<p><strong>Math.round() </strong>: Arredonda um valor real para inteiro. Se o valor da casa depois do ponto for maior ou igual a 5 é arredondado para cima, caso contrário para baixo;</p>
<pre name="code" class="js">
Math.round(4.5); // retorna 5
Math.round(3.49); // retorna 3
</pre>
<p><strong>Math.random()</strong> : Retorna um valor real e aleatório entre 0 e 1.</p>
<pre name="code" class="js">
Math.random(); // ex 0.56766776... (até 17 números depois do ponto)
</pre>
<p><strong>Math.max() </strong>: Retorna o número de maior valor entre dois.</p>
<pre name="code" class="js">
Math.max(4,7); // retorna 7
</pre>
<p><strong>Math.min()</strong> : Retorna o número de menor valor entre dois.</p>
<pre name="code" class="js">
Math.min(4,7); // retorna 4
</pre>
<p><strong>Constantes Matemáticas: </strong></p>
<pre name="code" class="js">
Math.E // valor de Euler (Oiler)
Math.PI // valor de PI
Math.SQRT2 // valor da raiz quadrada de 2
Math.SQRT1_2 // valor da raiz quadrada de 0.5 (1/2)
Math.LN2 // valor do Logaritmo Natural de 2 (ln 2)
Math.LN10 // valor do Logaritmo Natural de 10 (ln 10)
Math.LOG2E // valor do Logaritmo de E (Math.E) na base 2
Math.LOG10E // valor do Logaritmo de E na base 10.
</pre>
<p><strong>Veja em ação:</strong></p>
<p><a href="http://www17.brinkster.com/chivalrous/tutoriais/math.html" title="Classe Math" target="_blank">Clique aqui</a> para ver esses exemplos funcionando.</p>
]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2007/01/19/javascript-classe-math/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript: Classe Date()</title>
		<link>http://rogeriolino.com/2007/01/11/javascript-classe-date/</link>
		<comments>http://rogeriolino.com/2007/01/11/javascript-classe-date/#comments</comments>
		<pubDate>Thu, 11 Jan 2007 20:55:17 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[classe]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[horas]]></category>
		<category><![CDATA[hours]]></category>
		<category><![CDATA[mensagem]]></category>
		<category><![CDATA[minutes]]></category>
		<category><![CDATA[minutos]]></category>
		<category><![CDATA[seconds]]></category>
		<category><![CDATA[segundos]]></category>

		<guid isPermaLink="false">http://rogeriolino.wordpress.com/2007/01/11/javascript-classe-date/</guid>
		<description><![CDATA[<p>Uma classe muito funcional do Javascript e em muitas outras linguagens é a Date().</p> <p>Definindo um objeto como Date podemos pegar a hora, minutos, segundos, dia, mês, &#8230;, local ou do horário universal.</p> <p>Usando:</p> var minhaData = new Date(); var hora = minhaData.getHours(); window.alert( hora); <p>Será mostrado na janela de aviso a hora local.</p> <p>Podemos [...]]]></description>
			<content:encoded><![CDATA[<p>Uma classe muito funcional do Javascript e em muitas outras linguagens é a Date().</p>
<p>Definindo um objeto como Date podemos pegar a hora, minutos, segundos, dia, mês, &#8230;, local ou do horário universal.</p>
<p>Usando:</p>
<pre name="code" class="js">
var minhaData = new Date();
var hora = minhaData.getHours();
window.alert( hora);
</pre>
<p>Será mostrado na janela de aviso a hora local.</p>
<p>Podemos então aproveitar isso para mostrar uma mensagem (bom dia, boa tarde ou boa noite) para o usuário.</p>
<pre name="code" class="js">
var minhaData = new Date();
var hora = minhaData.getHours();
var msg = "Boa noite";
if ((hora &gt;= 6) &amp;&amp; (hora &lt; 12)) {
    msg = "Bom dia";
} else if ((hora &gt;= 12) &amp;&amp; (hora &lt; 18)) {
    msg = "Boa tarde";
}
window.alert(msg);
</pre>
<p>Define uma variável como Date(), e pegamos a hora local. O porquê da variavél msg receber &#8220;Boa noite&#8221; já vai dar para entender.</p>
<p>Perguntamos então se o valor de hora é maior ou igual a 6 e menor que 12 (6 a 11), então ainda é dia. Caso contrário pode ser noite ou tarde, por isso perguntamos se esse valor é maior igual a 12 ou menor que 18 (12 a 17), então é tarde.</p>
<p>Se não estiver entre os valores acima então é noite. Por isso já setamos a variável como &#8220;Boa noite&#8221;, só para economizar um else. =]</p>
<p>Brincando um pouco mais com a Classe Date fiz um simples relógio, e mostrar a data formatada no site (na página também há um link para explicação de cada função da classe). Para conferir segue o link: <a href="http://www17.brinkster.com/chivalrous/tutoriais/date.html" title="Classe Date()" target="_blank">Classe Date()</a>.</p>
<p><strong>Mais sobre:</strong></p>
<p><a href="http://www.w3schools.com/jsref/jsref_obj_date.asp" target="_blank">http://www.w3schools.com/jsref/jsref_obj_date.asp</a></p>
]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2007/01/11/javascript-classe-date/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

