<?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>Stiod Blog &#187; C/C++</title>
	<atom:link href="http://blog.stiod.com/category/cc/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.stiod.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Mon, 22 Feb 2010 14:20:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Make e Makefile</title>
		<link>http://blog.stiod.com/2009/11/25/make-e-makefile/</link>
		<comments>http://blog.stiod.com/2009/11/25/make-e-makefile/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 13:43:43 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[GNU]]></category>
		<category><![CDATA[make]]></category>
		<category><![CDATA[Makefile]]></category>
		<category><![CDATA[shell]]></category>

		<guid isPermaLink="false">http://blog.stiod.com/?p=719</guid>
		<description><![CDATA[Você que utiliza algum *nix da vida já deve ter passado pelo momento mágico de ter executado o comando make em algum código fonte, não?
O make (GNU make) é uma ferramenta que executa os comandos inclusos dentro de um arquivo. É normalmente utilizado na compilação e instalação de programas.
Uma das vantagens do make é que [...]]]></description>
			<content:encoded><![CDATA[<p>Você que utiliza algum *nix da vida já deve ter passado pelo momento mágico de ter executado o comando make em algum código fonte, não?</p>
<p>O <strong>make</strong> (<a href="http://www.gnu.org/software/make/">GNU make</a>) é uma ferramenta que executa os comandos inclusos dentro de um arquivo. É normalmente utilizado na <strong>compilação</strong> e <strong>instalação</strong> de programas.</p>
<p>Uma das vantagens do make é que ele identifica quais partes do programa devem ser recompiladas de acordo com as mudanças efetuadas desde a última compilação.</p>
<p>Dependendo do tamanho do programa pode-se economizar minutos ou horas entre as recompilações, pois não será necessário recompilar o programa inteiro.</p>
<p>Exemplo de uso:</p>
<pre class="bash">$ <span style="color: #c20cb9; font-weight: bold;">make</span> -f arquivo_com_os_comandos</pre>
<p></p>
<p>Se você chamar o comando make sem passar nenhum parâmetro ele tentará utilizar o arquivo com nome de <strong>Makefile</strong> do diretório atual.</p>
<p>É o que normalmente acontece quando você precisa compilar e instalar um programa pelo código fonte.</p>
<ul>
<li>Descompactar o código fonte (se for um "<strong>*.tar.gz</strong>").</li>
<li>Entrar na pasta descompactada. Haverá um arquivo <strong>Makefile</strong> dentro.</li>
<li>Executar o comando "<strong>make</strong>" para compilar.</li>
<li>Executar o comando "<strong>make install</strong>" como root para instalar.</li>
</ul>
<p></p>
<h3>Makefile</h3>
<p>Se você quiser utilizar o comando make só é necessário criar um arquivo <strong>Makefile</strong> e dentro dele colocar as instruções que o make deve executar.</p>
<p>Formato do Makefile:</p>
<pre>regra: dependências...
	comandos
	...</pre>
<p></p>
<p>Os <strong>comandos</strong> são comandos normais do <strong>shell</strong> (bash). Pode-se colocar vários comandos, porém devem estar <strong>identados com tabulações</strong>. Isto é importante, <strong>não utilize espaços</strong> pois não irá funcionar.</p>
<p>A <strong>regra</strong> é só um nome para identificar um bloco de comandos. Fazendo uma analogia com programação, a "regra" seria semelhante a uma função.</p>
<p>As <strong>dependências</strong> são os arquivos necessários para a execução dos comandos da regra, o make irá fazer a verificação deles. Também podem ser outras <strong>regras</strong> que serão chamadas antes da execução dos comandos. Se houver mais de uma dependência elas devem ser separadas com espaços.</p>
<p>Aqui vai um exemplo de um Makefile que compila um programa em C:</p>
<pre>program:
	gcc -o meuprograma meuprograma.c</pre>
<p></p>
<p>Um exemplo com dependências:</p>
<pre>program: cod1.c cod2.c lib1.a
	gcc -c cod1.c cod2.c
	gcc cod1.o cod2.o lib1.a -o program

lib1.a: lib1.c cod3.c
	gcc -c lib1.c cod3.c
	ar rcs lib1.a lib1.o cod3.o
	ranlib lib1.a</pre>
<p></p>
<p>Pode-se utilizar variáveis também. A declaração é simples, mas devem ser chamados com a notação "<strong>$(variável)</strong>". Repare também que elas podem ser concatenadas:</p>
<pre>CC=gcc
CFLAGS=-O2
CFLAGS=$(CFLAGS) -Wall

program:
	$(CC) $(CFLAGS) -o program program.c</pre>
<p></p>
<p>Olha que legal no Makefile a seguir, advinha o que acontece ao executar o comando `make clean' no terminal?</p>
<pre>program: program.c
        gcc -o program program.c

clean:
        rm *.o
        rm program</pre>
<p></p>
<p>O que aconteceria também se houvesse um arquivo no diretório atual que se chamasse "clean"? O `make clean' não iria executar a lista de comandos da regra. Para evitar este tipo de conflito utilize a regra "<strong>.PHONY</strong>":</p>
<pre>program: program.c
        gcc -o program program.c

.PHONY: clean
clean:
        rm *.o
        rm program</pre>
<p></p>
<p>Agora a regra "clean" será executada mesmo se houver um arquivo no diretório atual com mesmo nome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2009/11/25/make-e-makefile/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lendo o valor de um Endereço da memória em C++</title>
		<link>http://blog.stiod.com/2009/02/16/lendo-o-valor-de-um-endereco-da-memoria-em-c/</link>
		<comments>http://blog.stiod.com/2009/02/16/lendo-o-valor-de-um-endereco-da-memoria-em-c/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 22:32:22 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[C/C++]]></category>

		<guid isPermaLink="false">http://blog.stiod.com/?p=254</guid>
		<description><![CDATA[Para quem está estudando C++ aqui vai uma dica de como ler o valor de um endereço de memória. Basicamente o que vamos fazer são apenas conversões ou “casts” com os valores numéricos.

Por exemplo, para converter um “float” para “int” fazemos assim:
float a = 1.0;int b = &#40;int&#41; a;  // cast
Para transformar um número [...]]]></description>
			<content:encoded><![CDATA[<p>Para quem está estudando C++ aqui vai uma dica de como ler o valor de um endereço de memória. Basicamente o que vamos fazer são apenas conversões ou “casts” com os valores numéricos.<br />
<span id="more-254"></span><br />
Por exemplo, para converter um “float” para “int” fazemos assim:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">float</span> a = <span style="color: #cc66cc;">1.0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> b = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span><span style="color: #66cc66;">&#41;</span> a;  <span style="color: #808080; font-style: italic;">// cast</span></div></li></ol></pre>
<p>Para transformar um número em ponteiro é a mesma coisa, a diferença é que para ler a memória byte-a-byte o ponteiro deve ser um “char”. Por exemplo, um “(char*) 255” irá converter 255 para um ponteiro que aponta para o endereço 0xFF.</p>
<p>Mas nós só convertemos para ponteiro, para ler o conteúdo ainda é necessário colocar um “*” antes do ponteiro, como se faz normalmente para se ler o conteúdo de um ponteiro normal. Como é um ponteiro do tipo “char” o seu retorno pode ser exibido na tela.</p>
<p>Abaixo segue um programa que pede para o usuário digitar um endereço de memória em hexadecimal e quantidade de bytes que devem ser lidos, em seguida ele exibe o conteúdo da memória.</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include&lt;iostream&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include&lt;sstream&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">using namespace std;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">// Funcao para exibir apenas caracteres imprimiveis</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">char</span> ChangeToPrintable<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">char</span> C<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span>C &lt; <span style="color: #cc66cc;">32</span><span style="color: #66cc66;">&#41;</span> || <span style="color: #66cc66;">&#40;</span>C &gt; <span style="color: #cc66cc;">126</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>?<span style="color: #ff0000;">'?'</span>:C;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> main<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> argc, <span style="color: #993333;">char</span>** argv<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span> addr_i, i, len;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #993333;">string</span> addr_str;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    cout&lt;&lt;<span style="color: #ff0000;">&quot;Endereço de memória em hex.: &quot;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    cin&gt;&gt;addr_str;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    cout&lt;&lt;<span style="color: #ff0000;">&quot;Quantidade de bytes: &quot;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    cin&gt;&gt;len;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    cout&lt;&lt;endl;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// Converte a string hex. em inteiro</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    stringstream convert<span style="color: #66cc66;">&#40;</span>addr_str<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    convert&gt;&gt;hex&gt;&gt;addr_i;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">for</span><span style="color: #66cc66;">&#40;</span>i = addr_i; i &lt; <span style="color: #66cc66;">&#40;</span>addr_i + len<span style="color: #66cc66;">&#41;</span>; i++<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        cout&lt;&lt;ChangeToPrintable<span style="color: #66cc66;">&#40;</span>*<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#40;</span><span style="color: #993333;">char</span>*<span style="color: #66cc66;">&#41;</span> i<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    cout&lt;&lt;endl;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li></ol></pre>
<p>O interessante sobre o programa é que se ele rodar irá exibir um “segmentation fault”. Isso está correto, porque o sistema operacional não deve permitir que um programa leia (invada) a memória de outro. Mas você pode ler a memória alocada para o próprio programa que está rodando. Você pode tentar, por exemplo, ler a partir da área onde a função “main” está alocada, colocando o seguinte código antes do “for” que realiza a leitura dos dados:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">addr_i = <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">unsigned</span> <span style="color: #993333;">long</span><span style="color: #66cc66;">&#41;</span> &amp;main; <span style="color: #808080; font-style: italic;">// Converte o endereço para inteiro</span></div></li></ol></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2009/02/16/lendo-o-valor-de-um-endereco-da-memoria-em-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Internacionalização de software: i18n</title>
		<link>http://blog.stiod.com/2008/06/09/internacionalizacao-de-software/</link>
		<comments>http://blog.stiod.com/2008/06/09/internacionalizacao-de-software/#comments</comments>
		<pubDate>Mon, 09 Jun 2008 09:09:56 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://blog.stiod.com.br/?p=82</guid>
		<description><![CDATA[Fiquei um tempo sem colocar nada no blog, mas voltei. Recebi até um comunicado oficial do Rafael que se não colocasse nada no blog, era para pegar minhas coisas e passar no RH (ou era para passar no RH e depois pegar as minhas coisas?).
Introdução
Imagine que seu professor de linguagem C++ (ou outra de sua [...]]]></description>
			<content:encoded><![CDATA[<p><em>Fiquei um tempo sem colocar nada no blog, mas voltei. Recebi até um comunicado oficial do Rafael que se não colocasse nada no blog, era para pegar minhas coisas e passar no RH (ou era para passar no RH e depois pegar as minhas coisas?).</em></p>
<p><strong>Introdução</strong><br />
Imagine que seu professor de linguagem C++ (ou outra de sua preferência, mas uma linguagem descente, por favor) lhe passe uma lição de casa: “Faça um <a href="http://pt.wikipedia.org/wiki/MMORPG">MMORPG</a> em 5 idiomas diferentes”.<br />
Simples não? Qualquer um faz um MMORPG em C++ da noite para o dia. O detalhe desta simples aplicação é permitir a utilização ou diversão (já que é um game) em outros idiomas.<br />
Se você pensou em um colocar vários “IFs” ou “CASEs” para cada linha que contenha uma string...<br />
<span id="more-70"></span><br />
Bom, talvez não seja algo tão errado, se você tiver tempo para colocar vários “IFs” para cada uma das 4.000 strings de frases aleatórias dos <a href="http://pt.wikipedia.org/wiki/NPC">NPCs </a> do seu game. O trabalho todo será seu mesmo.<br />
Tudo bem, é só uma lição de casa, mas se não for pegue suas coisas e passe no RH (ou passe no RH e depois pegue as suas coisas... vocês entenderam né?).</p>
<p>Bom, sem encher muita lingüiça, vamos ao ponto: <strong>i18n</strong></p>
<p><strong>What?</strong><br />
<a href="http://pt.wikipedia.org/wiki/Internacionaliza%C3%A7%C3%A3o_(software)">i18n</a> é o acrônimo de <em>internacionalization</em> (“i” + 18 letras + “n”). As vantagens de se utilizar i18n são:</p>
<p>- O programa não precisa ser re-compilado a cada alteração nas traduções. Alternar entre os idiomas pode ser feito dinamicamente em tempo de execução (salvo algumas situações específicas).</p>
<p>- Este método é válido para muitas linguagens, não só o C++, o processo é praticamente o mesmo.</p>
<p>- Se o programa não conseguir encontrar a string traduzida ele exibirá a string original.</p>
<p>- A pessoa que fará as traduções não precisa entender de programação. Como o arquivo a ser traduzido está separado do programa, você pode mandar para um tradutor e depois só fazer as modificações necessárias para encaixar no programa (poucas coisas mesmo).</p>
<p>- Seu amigo chinês vai poder jogar seu game! De quebra ele indica o seu game para outros amiguinhos chineses que devem ser mais ou menos uns 10 mil só no bairro dele.</p>
<p>- Formatação correta de moeda, pesos, medidas, data, hora, etc. para o idioma escolhido.</p>
<p>- Aumento do alcance do seu programa/game em escala mundial. Para um alemão, nada melhor do que se utilizar um software em alemão. Para um brasileiro, nada melhor do que utilizar um software em português, não é?</p>
<p>- Perdão. Não existe nada melhor do que utilizar um software em português brasileiro (ora pois!).</p>
<p>- E outros benefícios que eu não me lembro ou não consegui inventar.</p>
<p><strong>Nada mastigado, apenas o caminho das pedras...</strong><br />
Mas como utilizar a/o i18n em meu programa? A melhor forma é utilizando o <a href="http://www.gnu.org/software/gettext/">gettext</a>. Seu uso é relativamente simples (claro, se você for um programador de verdade). Os passos e quesitos básicos para implementar as traduções são:</p>
<p>- O programa para estar perfeitamente internacionalizado deve ter suporte a caracteres UNICODE, mas tem que ter suporte de verdade ao UNICODE. Por exemplo, no Delphi só é possível manipular esses caracteres internamente sem poder exibi-los, pois os componentes dele não possuem suporte ao UNICODE (e vai saber quando terá de verdade). Mas você pode comprar componentes de terceiros com suporte a UNICODE, ou fazer que nem eu que alterei o componente TEdit na mão e fez o antivírus apitar na hora de rodar o programa (depois eu conto essa história).</p>
<p>- Instalar o gettext se você não tiver.</p>
<p>- Marcar no código as strings que serão traduzidas. Por exemplo:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Welcome to the Django Mr. %s!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, name<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p>se transforma em:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span>_<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Welcome to the Django Mr. %s!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>, name<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p>onde “_()” é uma função do gettext que marca a string para extração. Esta talvez seja a parte chata da coisa, mas não é tanto esforço assim.</p>
<p>- Um botão ou opção no seu programa para o usuário mudar o idioma.</p>
<p>- Extrair as strings (veja o manual do gettext). Será gerado um arquivo *.po com as strings marcadas.</p>
<p>- Traduzir as strings para um idioma em um editor de texto UNICODE. Utilizando o exemplo anterior ficaria assim:<br />
"Welcome to the Django Mr. %s!\n"<br />
"Bem-vindo a Djelva Sr. %s!\n"</p>
<p>- Compilar o arquivo traduzido com uma ferramenta apropriada, será gerado um arquivo *.mo. Uma ferramenta que utilizo para compilar e editar é o <a href="http://www.poedit.net/">Poedit</a>.</p>
<p>- Copiar o arquivo compilado para a pasta correta, normalmente (ou sempre) é em “diretório_do_programa/locale/sigla_do_idioma/LC_MESSAGES/default.mo”. Como em “meu_programa_bilingue/locale/pt_BR/LC_MESSAGES/default.mo”. Agora você sabe por que alguns programas com vários idiomas possuem uma pasta “locale” no diretório de instalação?</p>
<p>- Testar o seu programa.</p>
<p>- Para alterar a tradução basta editar apenas o *.po do idioma e compila-lo novamente, sem precisar mexer no código fonte do programa.</p>
<p>Basicamente, para cada idioma haverá um arquivo compilado diferente. De preferência, o idioma original do seu programa deve estar em inglês, mas nada impede que você o faça em português.</p>
<p><strong>Dicas</strong><br />
- Ao fazer a tradução procure fazer com que a tradução possua um tamanho próximo ao do original.</p>
<p>- No caso do Delphi você pode utilizar o <a href="http://dybdahl.dk/dxgettext/">dxgettext</a>, ele faz a captura automática das strings dos componentes. Infelizmente, faça uma boa leitura da documentação dele, pois existem alguns atributos de componentes que não devem ser traduzidos.</p>
<p>- Antes de fazer o seu programa estude (é estude!) um pouco sobre os idiomas que você irá disponibilizar em seu programa. Dependendo do idioma será necessário colocar algumas alterações no programa, como a escrita da direita-para-esquerda, de cima-para-baixo, etc. Não é nada muito difícil de fazer, muitas vezes isso é feito de forma automática pelo programa (depende muito da API utilizada) ou só mudar uma flag do componente que está utilizando (que também depende muito da API utilizada XD).</p>
<p>- Permita que o usuário escolha o idioma. Não obrigue ele a utilizar somente o idioma definido pelo SO. Eu mesmo já sofri muito com isso. :´(</p>
<p>- Para aplicações Desktop o ideal é que o texto possa fluir na tela de forma dinâmica, pois um texto pode aumentar ou diminuir de dimensões ao mudar de idioma, como de "texto romanizado" para "ideogramas chineses". Faça com que os itens da tela se redimensionem e se posicionem automaticamente. Uma boa opção é deixar com quebras de linhas automáticas, tomando o cuidado para que o texto não fique em cima de outros itens ao quebrar a linha.</p>
<p>Repare que só é possível fazer essas traduções com textos estáticos do programa. Se vierem dados do banco de dados já é mais complicado. A não ser que suas tabelas estejam bem modeladas, pelo menos na <a href="http://en.wikipedia.org/wiki/Third_normal_form">3NF</a> já daria para traduzir boa parte dos campos. Por exemplo, uma tabela de cores poderia ter os campos “cor_ptbr” e “cor_en”. Mas como fazer traduções corretamente de banco de dados isso eu deixo para próxima (pois nem eu sei XD).</p>
<p>Não entendeu nada do que falei? Clique <a href="http://www.google.com.br">aqui</a> que tudo ficará mais claro.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2008/06/09/internacionalizacao-de-software/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Sockets em C (WinSock)</title>
		<link>http://blog.stiod.com/2007/09/10/sockets-em-c-winsock/</link>
		<comments>http://blog.stiod.com/2007/09/10/sockets-em-c-winsock/#comments</comments>
		<pubDate>Mon, 10 Sep 2007 17:09:29 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://blog.stiod.com.br/?p=43</guid>
		<description><![CDATA[Um socket é um mecanismo de comunicação que permite que dois ou mais aplicativos troquem informações, seja no mesmo computador ou em computadores distintos, como os programas de chats, games on-line, navegadores, etc. No geral, programas que utilizam Network Communication ou Interprocess Communication utilizam sockets.
Sockets são importantes, por isso eu tinha que tomar vergonha na [...]]]></description>
			<content:encoded><![CDATA[<p>Um socket é um mecanismo de comunicação que permite que dois ou mais aplicativos troquem informações, seja no mesmo computador ou em computadores distintos, como os programas de chats, games on-line, navegadores, etc. No geral, programas que utilizam <em>Network Communication</em> ou <em>Interprocess Communication</em> utilizam sockets.</p>
<p>Sockets são importantes, por isso eu tinha que tomar vergonha na cara e aprender a usá-los, comecei a ler sobre o assunto e consegui fazer uma pequena aplicação que envia mensagens para outra.<br />
<span id="more-33"></span><br />
Primeiramente vou mostrar o código e depois ir (tentando) descrever as funções. Não vou me aprofundar, é só para ter uma idéia de como a coisa funciona, mesmo porque eu acho que aprofundei demais na explicação (mas quanto mais se sabe, mas se sabe que não se sabe nada XD).</p>
<p>O código foi feito para Windows, mas a implementação no Linux é bem parecida. No Windows você deve usar a <strong>WinSock API</strong> para trabalhar com sockets, não se esqueça de linkar a lib na hora de compilar. Eu uso o Dev-C++ e a lib é a <strong>libwsock32.a</strong>.</p>
<h3>Criando o servidor que recebe mensagens</h3>
<p><br/></p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">/*</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">&nbsp;   SERVIDOR</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">*/</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;stdlib.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;string.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;winsock.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#define BACKLOG_MAX 5</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#define BUFFER_SIZE 128</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#define EXIT_CALL_STRING &quot;#quit&quot;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> local_socket = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> remote_socket = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> remote_length = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> message_length = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">unsigned</span> <span style="color: #993333;">short</span> local_port = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">unsigned</span> <span style="color: #993333;">short</span> remote_port = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">char</span> message<span style="color: #66cc66;">&#91;</span>BUFFER_SIZE<span style="color: #66cc66;">&#93;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">struct</span> sockaddr_in local_address;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">struct</span> sockaddr_in remote_address;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">WSADATA wsa_data;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">/* Exibe uma mensagem de erro e termina o programa */</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">void</span> msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">char</span> *msg<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    fprintf<span style="color: #66cc66;">&#40;</span>stderr, msg<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    system<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;PAUSE&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    exit<span style="color: #66cc66;">&#40;</span>EXIT_FAILURE<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> main<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> argc, <span style="color: #993333;">char</span> **argv<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// inicia o Winsock 2.0 (DLL), Only for Windows</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>WSAStartup<span style="color: #66cc66;">&#40;</span>MAKEWORD<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>, &amp;wsa_data<span style="color: #66cc66;">&#41;</span> != <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;WSAStartup() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// criando o socket local para o servidor</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    local_socket = socket<span style="color: #66cc66;">&#40;</span>AF_INET, SOCK_STREAM, IPPROTO_TCP<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>local_socket == INVALID_SOCKET<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;socket() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Porta local: &quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    scanf<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;%d&quot;</span>, &amp;local_port<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    fflush<span style="color: #66cc66;">&#40;</span>stdin<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// zera a estrutura local_address</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    memset<span style="color: #66cc66;">&#40;</span>&amp;local_address, <span style="color: #cc66cc;">0</span>, <span style="color: #993333;">sizeof</span><span style="color: #66cc66;">&#40;</span>local_address<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// internet address family</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    local_address.<span style="color: #202020;">sin_family</span> = AF_INET;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// porta local</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    local_address.<span style="color: #202020;">sin_port</span> = htons<span style="color: #66cc66;">&#40;</span>local_port<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// endereco</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    local_address.<span style="color: #202020;">sin_addr</span>.<span style="color: #202020;">s_addr</span> = htonl<span style="color: #66cc66;">&#40;</span>INADDR_ANY<span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// inet_addr(&quot;127.0.0.1&quot;)</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// interligando o socket com o endereço (local)</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>bind<span style="color: #66cc66;">&#40;</span>local_socket, <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">struct</span> sockaddr *<span style="color: #66cc66;">&#41;</span> &amp;local_address, <span style="color: #993333;">sizeof</span><span style="color: #66cc66;">&#40;</span>local_address<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> == SOCKET_ERROR<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        closesocket<span style="color: #66cc66;">&#40;</span>local_socket<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;bind() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// coloca o socket para escutar as conexoes</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>listen<span style="color: #66cc66;">&#40;</span>local_socket, BACKLOG_MAX<span style="color: #66cc66;">&#41;</span> == SOCKET_ERROR<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        closesocket<span style="color: #66cc66;">&#40;</span>local_socket<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;listen() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    remote_length = <span style="color: #993333;">sizeof</span><span style="color: #66cc66;">&#40;</span>remote_address<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;aguardando alguma conexao...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    remote_socket = accept<span style="color: #66cc66;">&#40;</span>local_socket, <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">struct</span> sockaddr *<span style="color: #66cc66;">&#41;</span> &amp;remote_address, &amp;remote_length<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>remote_socket == INVALID_SOCKET<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        closesocket<span style="color: #66cc66;">&#40;</span>local_socket<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;accept() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;conexao estabelecida com %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, inet_ntoa<span style="color: #66cc66;">&#40;</span>remote_address.<span style="color: #202020;">sin_addr</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;aguardando mensagens...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">do</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #808080; font-style: italic;">// limpa o buffer</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        memset<span style="color: #66cc66;">&#40;</span>&amp;message, <span style="color: #cc66cc;">0</span>, BUFFER_SIZE<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #808080; font-style: italic;">// recebe a mensagem do cliente</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        message_length = recv<span style="color: #66cc66;">&#40;</span>remote_socket, message, BUFFER_SIZE, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>message_length == SOCKET_ERROR<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">            msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;recv() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #808080; font-style: italic;">// exibe a mensagem na tela</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;%s: %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, inet_ntoa<span style="color: #66cc66;">&#40;</span>remote_address.<span style="color: #202020;">sin_addr</span><span style="color: #66cc66;">&#41;</span>, message<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">while</span><span style="color: #66cc66;">&#40;</span>strcmp<span style="color: #66cc66;">&#40;</span>message, EXIT_CALL_STRING<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// sai quando receber um &quot;#quit&quot; do cliente</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;encerrando<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    closesocket<span style="color: #66cc66;">&#40;</span>local_socket<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    closesocket<span style="color: #66cc66;">&#40;</span>remote_socket<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    system<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;PAUSE&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li></ol></pre>
<p><br/></p>
<h4>WSAStartup()</h4>
<p>A função <strong>WSAStartup()</strong> inicia o <em>Windows Sockets Dynamic Link</em> (WinSock DLL). Ela também é usada para confirma a versão do WinSock DLL. Estamos utilizando a 2.0.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> WSAStartup<span style="color: #66cc66;">&#40;</span>WORD wVersionRequested, LPWSADATA lpWSAData<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>O parâmetro <strong>wVersionRequested</strong> é número da maior versão que a aplicação pode usar. Repare que ele é uma <strong>WORD</strong> onde o byte de maior ordem especifica a número da minor version e o byte de ordem menor indica a major version. Por isso eu utilizo a função <strong>MAKEWORD</strong> para retornar uma <strong>WORD</strong> (e facilitar minha vida), por exemplo, se quiser usar a versão do WinSock 1.1 é só alterar para <strong>MAKEWORD(1, 1)</strong>. Fácil demais...</p>
<p>O parâmetro <strong>lpWSAData</strong> é um ponteiro para um estrutura <strong>WSADATA</strong> que receberá os detalhes da implementação do WinSock.</p>
<p>Se der tudo certo a função retornará 0. Se ocorrer um erro você pode usar a função <strong>WSAGetLastError()</strong> para saber mais detalhes.</p>
<h4>socket()</h4>
<p>Use a função <strong>socket()</strong> parar criar o socket \o/.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">SOCKET WSAAPI socket<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> af, <span style="color: #993333;">int</span> type, <span style="color: #993333;">int</span> protocol<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>O parâmetro <strong>af</strong> especifica o "address family" que este socket usa. Nós iremos usar o <strong>AF_INET</strong>. A versão 1.1 do WinSock só suporta o formato <strong>AF_INET</strong>.</p>
<p>Alguns formatos possíveis:<br />
<small><strong>AF_INET</strong>: Arpa Internet Protocols<br />
<strong>AF_UNIX</strong>: Unix Internet Protocols<br />
<strong>AF_ISSO</strong>: Iso Protocols<br />
<strong>AF_NS</strong>: Xerox Network System Protocols</small></p>
<p>Se você olhar no header (winsock.h) vai encontrar outros como o <strong>AF_FIREFOX</strong>, mas é melhor ver quais realmente podem ser usados no <a href="http://msdn2.microsoft.com/en-us/library/ms741416.aspx" target="_blank">MSDN</a>.</p>
<p>O parâmetro <strong>type</strong> especifica o tipo do socket, no nosso caso é <strong>SOCK_STREAM</strong> (utilizado na maioria dos programas), mas você pode usar o <strong>SOCK_DGRAM</strong> (<strong>UDP</strong>), mas não vou abordar as diferenças entre eles.</p>
<p>Em <strong>protocol</strong> deixe 0 (zero), isto indica que o socket irá usar o valor padrão. O <strong>protocol</strong> pode ser o padrão porque a combinação do <strong>AF_INET</strong>+<strong>SOCK_STREAM</strong> já indica que o protocolo é TCP. Eu coloquei <strong>IPPROTO_TCP</strong> no código, mas não precisa, é só deixar como 0.</p>
<p>Alguns valores possíveis para o protocol:<br />
<small><strong>IPPROTO_IP</strong>: Internet Protocol (0)<br />
<strong>IPPROTO_ICMP</strong>: Internet Control Message Protocol (1)<br />
<strong>IPPROTO_IGMP</strong>: Internet Group Multicast Protocol (2)<br />
<strong>IPPROTO_GGP</strong>: Gateway-Gateway Protocol (3)<br />
<strong>IPPROTO_TCP</strong>: Transmission Control Protocol (6)<br />
<strong>IPPROTO_UDP</strong>: User Datagrama Protocol (17)</small></p>
<p>Se der tudo certo a função irá retornar o <strong>socket descriptor</strong>, que é um número que identifica o socket criado. Se falhar irá retorna <strong>INVALID_SOCKET</strong>, você pode usar a função <strong>WSAGetLastError()</strong> para saber mais detalhes do erro.</p>
<h4>bind()</h4>
<p>Agora precisamos dar nomes aos bois, precisamos dizer que o nosso socket se chama "192.168.0.1", por exemplo. Usaremos a função <strong>bind()</strong> para isso.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> bind<span style="color: #66cc66;">&#40;</span>SOCKET s, <span style="color: #993333;">const</span> <span style="color: #993333;">struct</span> sockaddr *addr, <span style="color: #993333;">int</span> namelen<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>O parâmetro <strong>s</strong> é o <strong>socket descriptor</strong> retornado pela função <strong>socket()</strong>. O parâmetro <strong>addr</strong> é um ponteiro para uma estrutura do tipo <strong>sockaddr</strong>. O <strong>namelen</strong> é o tamanho em bytes da estrutura, use a função <strong>sizeof()</strong> para isto.</p>
<p>Esta parte pode confundir, antes de usar a função <strong>bind()</strong> nós precisamos conhecer as estruturas <strong>sockaddr</strong>, <strong>sockaddr_in</strong> e <strong>in_addr</strong>, mas a que iremos utilizar é a <strong>sockaddr_in</strong>.</p>
<p>Definições da estrutura <strong>sockaddr</strong>:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">struct</span> sockaddr</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    u_short sa_family; <span style="color: #808080; font-style: italic;">// address family</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #993333;">char</span> sa_data<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">14</span><span style="color: #66cc66;">&#93;</span>; <span style="color: #808080; font-style: italic;">// address</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span>;</div></li></ol></pre>
<p><br/></p>
<p>O item <strong>sa_data</strong> da estrutura vai depende do "address family". No WinSock 1.1, como eu disse, apenas o <strong>AF_INET</strong> é suportado, logo somente um "endereçamento de internet" é suportado no <strong>sa_data</strong>. Lembrando que você não vai utilizar esta estrutura, mas eu coloquei porque ela aparece em um "cast" de um dos parâmetros da função <strong>bind()</strong> que estamos utilizando. Você deve utilizar uma outra estrutura no lugar da <strong>sockaddr</strong> quando chamar a função <strong>bind()</strong>, use a <strong>sockaddr_in</strong>.</p>
<p>Definições da estrutura <strong>sockaddr_in</strong>:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">struct</span> sockaddr_in</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #993333;">short</span> sin_family; <span style="color: #808080; font-style: italic;">// address family</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    u_short sin_port; <span style="color: #808080; font-style: italic;">// port</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #993333;">struct</span> in_addr sin_addr; <span style="color: #808080; font-style: italic;">// internet address</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #993333;">char</span> sin_zero<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">8</span><span style="color: #66cc66;">&#93;</span>; <span style="color: #808080; font-style: italic;">// to make a beautiful cast</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span>;</div></li></ol></pre>
<p><br/></p>
<p>Primeiro você deve zerar a estrutura e depois preencher alguns itens. No código que eu fiz está assim:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">struct</span> sockaddr_in local_address;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">/* ... */</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">memset<span style="color: #66cc66;">&#40;</span>&amp;local_address, <span style="color: #cc66cc;">0</span>, <span style="color: #993333;">sizeof</span><span style="color: #66cc66;">&#40;</span>local_address<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// zera a estrutura</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">local_address.<span style="color: #202020;">sin_family</span> = AF_INET;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">local_address.<span style="color: #202020;">sin_port</span> = htons<span style="color: #66cc66;">&#40;</span>local_port<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">local_address.<span style="color: #202020;">sin_addr</span>.<span style="color: #202020;">s_addr</span> = htonl<span style="color: #66cc66;">&#40;</span>INADDR_ANY<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p><strong>Importante!</strong><br />
Nem todos os computadores armazenam os dados na mesma ordem na memória. Existem computadores que trabalham no formato "Big Endian", onde byte menos significativo fica no endereço de memória de maior valor. Por exemplo, para armazenar o número <strong>0x01234567</strong> ficaria assim:<br />
<small><strong>endereço 0x101</strong>: 01<br />
<strong>endereço 0x102</strong>: 23<br />
<strong>endereço 0x103</strong>: 45<br />
<strong>endereço 0x104</strong>: 67</small</p>
<p>O maior endereço é o <strong>0x104</strong> e o byte menos significativo de <strong>0x01234567</strong> é o último da direita (67).</p>
<p>Já nos computadores "Little Endian", ocorre o inverso, o byte menos significativo fica no endereço de memória de menor valor:<br />
<small><strong>endereço 0x101</strong>: 67<br />
<strong>endereço 0x102</strong>: 45<br />
<strong>endereço 0x103</strong>: 23<br />
<strong>endereço 0x104</strong>: 01</small><br />
O menor endereço é o <strong>0x101</strong> e o byte menos significativo de <strong>0x01234567</strong> é o último da direita (67).</small></p>
<p>Os computadores com processadores baseados no Intel x86 são "Little Endian", mas a ordem dos bytes na rede (network) é "Big Endian". Precisamos converter os dados antes de enviá-los usando as funções <strong>htons()</strong> e <strong>htonl()</strong>:<br />
<small><strong>htons()</strong>: converte um <strong>unsigned short</strong> (host-to-network)<br />
<strong>htonl()</strong>: converte um <strong>unsigned long</strong> (host-to-network)</small></p>
<p>Existem outras funções para esta converter os dados, mas nós iremos utilizar apenas esses.</p>
<p>Voltando a estrutura <strong>sockaddr_in</strong>, vamos falar do item <strong>sin_addr</strong>. Veja na declaração que este item é uma estrutura do tipo <strong>in_ddr</strong>.</p>
<p>Definições da estrutura <strong>in_addr</strong>:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">struct</span> in_addr</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #993333;">union</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #993333;">struct</span> <span style="color: #66cc66;">&#123;</span> u_char s_b1,s_b2,s_b3,s_b4; <span style="color: #66cc66;">&#125;</span> S_un_b;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #993333;">struct</span> <span style="color: #66cc66;">&#123;</span> u_short s_w1,s_w2; <span style="color: #66cc66;">&#125;</span> S_un_w;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        u_long S_addr;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span> S_un;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #339933;">#define s_addr S_un.S_addr</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #339933;">#define s_host S_un.S_un_b.s_b2</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #339933;">#define s_net S_un.S_un_b.s_b1</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #339933;">#define s_imp S_un.S_un_w.s_w2</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #339933;">#define s_impno S_un.S_un_b.s_b4</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #339933;">#define s_lh S_un.S_un_b.s_b3</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span>;</div></li></ol></pre>
<p><br/></p>
<p>Repare nos <em>defines</em> que ela possui, você pode acessar o dados da estrutura através deles. Quando você acessa <strong>local_address.sin_addr.s_addr</strong> na verdade esta acessando <strong>local_address.sin_addr.S_un.S_addr</strong>. Mas sempre use os <em>defines</em> para manter compatibilidade, não acesse os dados diretamente.</p>
<p>O valor indicado para <strong>local_address.sin_addr.s_addr</strong> é <strong>htonl(INADDR_ANY)</strong>, isto indica que usaremos todos os endereços locais designados ao nosso servidor. Por exemplo, se sua máquina possui duas placas de rede (192.168.0.1 e 192.168.0.2), você pode usar os dois endereços para o seu socket. Mas se você quiser especificar apenas uma placa, use a função <strong>inet_addr()</strong>. Nós usaremos esta função para fazer o programa cliente.</p>
<p>Sobre o item <strong>sin_zero</strong> da estrutura <strong>sockaddr_in</strong>, ele server apenas para ocupar espaço, de modo que a estrutura tenha o mesmo tamanho (em bytes) da estrutura <strong>sockaddr</strong>. Assim podemos fazer "casts" de uma estrutura para outra (utilizado no parâmetro da função <strong>bind()</strong>). Por isso a estrutura deve ser preenchida com zeros antes de ser utilizada.</p>
<p>Se der tudo certo a função <strong>bind()</strong> retornará 0, caso contrário retornará <strong>SOCKET_ERROR</strong>, use o <strong>WSAGetLastError()</strong> para analisar o erro.</p>
<h4>listen()</h4>
<p>A função <strong>listen()</strong> coloca o socket para escutar as conexões. Seria como ligar o socket, agora ele pode receber por conexões dos clientes.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> listen<span style="color: #66cc66;">&#40;</span>SOCKET s, <span style="color: #993333;">int</span> backlog<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>O parâmetro <strong>s</strong> é o <strong>socket descriptor</strong> que você já conhece. O <strong>backlog</strong> indica quantas conexões pendentes o socket pode deixar na fila para serem processadas, quando as conexões são aceitas elas são removidas da fila. O mínimo para o <strong>backlog</strong> é 1 e o máximo 5, mas não achei alguma coisa no site do MSDN que indicasse que o limite é sempre 5.</p>
<p>Se tudo der certo ele vai retornar 0, caso contrário ele retornará um <strong>SOCKET_ERROR</strong>. Novamente você pode usar a função <strong>WSAGetLastError()</strong> para analisar o erro se quiser.</p>
<h4>accept()</h4>
<p>O <strong>accept()</strong> aceita a conexão quando ela é detectada.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">SOCKET accept<span style="color: #66cc66;">&#40;</span>SOCKET s, <span style="color: #993333;">struct</span> sockaddr* addr, <span style="color: #993333;">int</span>* addrlen<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>O parâmetro <strong>s</strong> é o <strong>socket descriptor</strong>. O parâmetro <strong>addr</strong> é um ponteiro para uma estrutura do tipo <strong>sockaddr</strong> (igual ao do função <strong>bind()</strong>), nela a função irá armazenar a o endereço (estrutura) da entidade (cliente) que requisitou a conexão. Você não precisa armazenar este valor se não quiser obter informações do cliente, pode colocar apenas um NULL no lugar.</p>
<p>O parâmetro <strong>addrlen</strong> é um ponteiro onde a função irá colocar o tamanho em bytes da estrutura <strong>addr</strong> recebida do cliente. Se você passar um NULL para o parâmetro <strong>addr</strong> então o <strong>addrlen</strong> retornará NULL para o ponteiro. Você também pode apenas colocar um NULL no parâmetro do <strong>addrlen</strong>.</p>
<p>Repare que o programa ficará esperando por uma conexão, ele ficará meio travado enquanto isso. Você terá que fazer ele rodar de forma assíncrona, mas isso não é importante agora, primeiro temos que fazer o servidor e o cliente funcionarem.</p>
<p>A função <strong>accept()</strong> irá retornar um <strong>socket descriptor</strong> do cliente. Se der algum problema será retornado um <strong>INVALID_SOCKET</strong>. Novamente use o <strong>WSAGetLastError()</strong> para verificar os erros.</p>
<h4>recv()</h4>
<p>O <strong>recv()</strong> recebe os dados de uma conexão.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> recv<span style="color: #66cc66;">&#40;</span>SOCKET s, <span style="color: #993333;">char</span>* buf, <span style="color: #993333;">int</span> len, <span style="color: #993333;">int</span> flags<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>O parâmetro <strong>s</strong> é o <strong>socket descriptor</strong> do cliente. O parâmetro <strong>buf</strong> é o buffer onde serão armazenadas as informações recebidas. O <strong>len</strong> é o tamanho deste buffer.</p>
<p>O parâmetro <strong>flags</strong> indica o modo como serão recebidos os dados, eu deixei como 0 (zero) assim ele não fará nenhuma ação especial. Para mais detalhes sobre outras opções olhe no site <a href="http://msdn2.microsoft.com/en-us/library/ms741416.aspx" target="_blank">MSDN</a>.</p>
<p>O <strong>recv()</strong> irá retornar o total de bytes recebidos, mas você não irá receber mais bytes do que especificou em len. Ele retorna 0 (zero) quando a conexão é fechada normalmente. Se der algum erro ele retorna um <strong>SOCKET_ERROR</strong>. Use o <strong>WSAGetLastError()</strong> para saber mais do erro.</p>
<p>Repare que eu também usei a função <strong>inet_ntoa()</strong> para exibir junto com a mensagem. Essa função converte um endereço de Internet (IPv4) em uma string do endereço formatado nos padrões de Internet com pontos decimais. Ela já retorna em "Little Endian".</p>
<p>O <strong>recv()</strong> está dentro de um loop, antes de receber uma mensagem o buffer (variável <strong>message</strong> no código) deverá ser limpo. Após receber a mensagem, ela é exibida. O loop só pára quando o cliente enviar uma mensagem "#quit". Não é a melhor maneira de ser terminar o programa, mas serve por enquanto.</p>
<p>Depois de tudo pronto, nós devemos finalizar a aplicação com as funções <strong>WSACleanup()</strong> e <strong>closesocket()</strong>. Você só precisa olhar o código para entender como usa-las. E é isso, o micro-nano-humilde-servidor tá pronto agora só falta fazer o cliente.</p>
<h3>Criando cliente que envia as mensagens</h3>
<p><br/></p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">/*</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">&nbsp;   CLIENTE</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">*/</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;stdlib.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;string.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#include &lt;winsock.h&gt;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#define BUFFER_SIZE 128</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #339933;">#define EXIT_CALL_STRING &quot;#quit&quot;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> remote_socket = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> message_length = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">unsigned</span> <span style="color: #993333;">short</span> remote_port = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">char</span> remote_ip<span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">32</span><span style="color: #66cc66;">&#93;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">char</span> message<span style="color: #66cc66;">&#91;</span>BUFFER_SIZE<span style="color: #66cc66;">&#93;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">struct</span> sockaddr_in remote_address;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">WSADATA wsa_data;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">/* Exibe uma mensagem de erro e termina o programa */</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">void</span> msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">char</span> *msg<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    fprintf<span style="color: #66cc66;">&#40;</span>stderr, msg<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    system<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;PAUSE&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    exit<span style="color: #66cc66;">&#40;</span>EXIT_FAILURE<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> main<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> argc, <span style="color: #993333;">char</span> **argv<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>WSAStartup<span style="color: #66cc66;">&#40;</span>MAKEWORD<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>, &amp;wsa_data<span style="color: #66cc66;">&#41;</span> != <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;WSAStartup() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;IP do servidor: &quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    scanf<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;%s&quot;</span>, remote_ip<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    fflush<span style="color: #66cc66;">&#40;</span>stdin<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;Porta do servidor: &quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    scanf<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;%d&quot;</span>, &amp;remote_port<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    fflush<span style="color: #66cc66;">&#40;</span>stdin<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    remote_socket = socket<span style="color: #66cc66;">&#40;</span>AF_INET, SOCK_STREAM, IPPROTO_TCP<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>remote_socket == INVALID_SOCKET<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;socket() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #808080; font-style: italic;">// preenchendo o remote_address (servidor)</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    memset<span style="color: #66cc66;">&#40;</span>&amp;remote_address, <span style="color: #cc66cc;">0</span>, <span style="color: #993333;">sizeof</span><span style="color: #66cc66;">&#40;</span>remote_address<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    remote_address.<span style="color: #202020;">sin_family</span> = AF_INET;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    remote_address.<span style="color: #202020;">sin_addr</span>.<span style="color: #202020;">s_addr</span> = inet_addr<span style="color: #66cc66;">&#40;</span>remote_ip<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    remote_address.<span style="color: #202020;">sin_port</span> = htons<span style="color: #66cc66;">&#40;</span>remote_port<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;conectando ao servidor %s...<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, remote_ip<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>connect<span style="color: #66cc66;">&#40;</span>remote_socket, <span style="color: #66cc66;">&#40;</span><span style="color: #993333;">struct</span> sockaddr *<span style="color: #66cc66;">&#41;</span> &amp;remote_address, <span style="color: #993333;">sizeof</span><span style="color: #66cc66;">&#40;</span>remote_address<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span> == SOCKET_ERROR<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;connect() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;digite as mensagens<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">do</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #808080; font-style: italic;">// limpa o buffer</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        memset<span style="color: #66cc66;">&#40;</span>&amp;message, <span style="color: #cc66cc;">0</span>, BUFFER_SIZE<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;msg: &quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        gets<span style="color: #66cc66;">&#40;</span>message<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        fflush<span style="color: #66cc66;">&#40;</span>stdin<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        message_length = strlen<span style="color: #66cc66;">&#40;</span>message<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #808080; font-style: italic;">// envia a mensagem para o servidor</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span>send<span style="color: #66cc66;">&#40;</span>remote_socket, message, message_length, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span> == SOCKET_ERROR<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">            WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">            closesocket<span style="color: #66cc66;">&#40;</span>remote_socket<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">            msg_err_exit<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;send() failed<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">while</span><span style="color: #66cc66;">&#40;</span>strcmp<span style="color: #66cc66;">&#40;</span>message, EXIT_CALL_STRING<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// sai quando enviar um &quot;#quit&quot; para o servidor</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;encerrando<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    WSACleanup<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    closesocket<span style="color: #66cc66;">&#40;</span>remote_socket<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    system<span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;PAUSE&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li></ol></pre>
<p><br/></p>
<p>Essa parte vai ser mais rápida, pois já vimos o básico sobre sockets no servidor.</p>
<p>Você deve criar um socket no cliente para poder conectar ao servidor. Ele precisa preencher uma estrutura do tipo <strong>socketaddr_in</strong> (que nós já vimos) com as informações do servidor, olhe o código para entender melhor.</p>
<h4>connect()</h4>
<p>A função <strong>connect()</strong> irá conectar o cliente com o servidor.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> connect<span style="color: #66cc66;">&#40;</span>SOCKET s, <span style="color: #993333;">const</span> <span style="color: #993333;">struct</span> sockaddr* name, <span style="color: #993333;">int</span> namelen<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>Ele recebe parâmetros iguais ao da função <strong>bind()</strong>. Se der algum erro ele retorna um <strong>SOCKET_ERROR</strong>.</p>
<p>A função <strong>connect()</strong> tem o mesmo problema da função <strong>accept()</strong>, enquanto ele estiver tentando conectar ficará travado (precisa ser assíncrono), mas não vou mostra como se faz isso, fica como lição de casa XD.</p>
<h4>send()</h4>
<p>E o <strong>send()</strong> é a função responsável por enviar informações ao servidor.</p>
<p>Declaração:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> send<span style="color: #66cc66;">&#40;</span>SOCKET s, <span style="color: #993333;">const</span> <span style="color: #993333;">char</span>* buf, <span style="color: #993333;">int</span> len, <span style="color: #993333;">int</span> flags<span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>Os parâmetro que ele recebe também são iguais ao da função <strong>recv()</strong>. O <strong>send()</strong> retonará o número de bytes enviados, esse número não será maior do <strong>len</strong> (e ele não enviará mais o que o especificado em <strong>len</strong>). Se der um erro ele retornará <strong>SOCKET_ERROR</strong>. Use o <strong>WSAGetLastError()</strong> para mais informações.</p>
<p>Lembre-se de limpar o buffer de mensagens, senão você irá enviar "lixo" para o servidor.</p>
<h4>Pronto!</h4>
<p>Compile os dois programas, depois execute primeiro o servidor depois o cliente. Se estiver rodando na mesma máquina você pode conectar o cliente no IP "127.0.0.1" que dará no mesmo. E é só isso, fácil demais não?</p>
<p>Para saber mais informações sobre o WinSock visite a página de referência da MSDN em <a href="http://msdn2.microsoft.com/en-us/library/ms741416.aspx" target="_blank">Winsock Reference</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2007/09/10/sockets-em-c-winsock/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Templates em C++</title>
		<link>http://blog.stiod.com/2007/07/16/templates-em-c/</link>
		<comments>http://blog.stiod.com/2007/07/16/templates-em-c/#comments</comments>
		<pubDate>Tue, 17 Jul 2007 01:58:15 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[C/C++]]></category>

		<guid isPermaLink="false">http://blog.stiod.com.br/?p=29</guid>
		<description><![CDATA[Uma das coisas mais estranhas do C++ pra mim são os templates, a sua sintaxe não é lá muito intuitiva (mas já vi coisas piores). Mas os templates são importantes, na verdade foram graças aos templates em C++ que a programação genérica se fortaleceu.

Um template lembra um define, só que bem mais “parrudo” e seguro. [...]]]></description>
			<content:encoded><![CDATA[<p>Uma das coisas mais estranhas do C++ pra mim são os templates, a sua sintaxe não é lá muito intuitiva (mas já vi coisas piores). Mas os templates são importantes, na verdade foram graças aos templates em C++ que a programação genérica se fortaleceu.<br />
<span id="more-22"></span><br />
Um template lembra um define, só que bem mais “parrudo” e seguro. Imagine que você tenha duas funções que some dois números cada, a primeira função serve para somar dois números inteiros e a segunda soma dois números de ponto flutuante.</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> soma_int<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">int</span> a, <span style="color: #993333;">int</span> b<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #66cc66;">&#40;</span>a + b<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">float</span> soma_float<span style="color: #66cc66;">&#40;</span><span style="color: #993333;">float</span> a, <span style="color: #993333;">float</span> b<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #66cc66;">&#40;</span>a + b<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">soma_int<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// retorna 30</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">soma_float<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10.12</span>, <span style="color: #cc66cc;">20.34</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// retorna 30.46</span></div></li></ol></pre>
<p><br/></p>
<p>Com os templates é possível criar uma única função que some estes números mesmo que sejam de tipos diferentes de dados.<br />
Basicamente para se criar uma função template é preciso ter a seguinte sintaxe:</p>
<p><strong><font color="#000088">template &lt;class</font></strong> <font color="#008800">identificador</font><strong><font color="#000088">&gt;</font></strong> <font color="#008800">declaração_da_função</font><strong><font color="#000088">;</font></strong></p>
<p>Utilizando o template no código anterior ele ficaria assim:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">template &lt;class T&gt;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">T soma<span style="color: #66cc66;">&#40;</span>T a, T b<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #66cc66;">&#40;</span>a + b<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">soma&lt;int&gt; <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// retorna 30</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">soma&lt;float&gt; <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10.12</span>, <span style="color: #cc66cc;">20.34</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// retorna 30.46</span></div></li></ol></pre>
<p><br/></p>
<p>O código ficou menor, pois eu só precisei criar uma função. Com uma explicação bem tosca eu poderia dizer que o compilador troca todos os "T" da função template pelo que estiver entre os sinais de maior e menor na hora que você chama a função (soma&lt;int&gt;, soma&lt;float&gt;). É parecido com o define, porém os templates possuem checagem de tipagem de dados, são bem mais versáteis e evitam que se cometam erros bobos com o uso de defines em excesso.</p>
<p>Se os parâmetros da função são de apenas 1 tipo não é necessário especificar com o &lt;int&gt; ou &lt;float&gt;, o compilador já deduz o tipo:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">soma<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// OK, os dois parâmetros são int</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">soma<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10.12</span>, <span style="color: #cc66cc;">20.34</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// OK, os dois parâmetros são float</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">soma<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">20.34</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// ERROR, os dois parâmetros são de tipos diferentes</span></div></li></ol></pre>
<p><br/></p>
<p>Você também pode especificar mais tipos para o template:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">template &lt;class TValue, class TPercent, class TReturn&gt;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">TReturn get_percentage<span style="color: #66cc66;">&#40;</span>TValue value, TPercent percentage<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #b1b100;">return</span> <span style="color: #66cc66;">&#40;</span>TReturn<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#40;</span>value * <span style="color: #66cc66;">&#40;</span>percentage / <span style="color: #cc66cc;">100.0</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">get_percentage&lt;int, <span style="color: #993333;">float</span>, int&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1000</span>, <span style="color: #cc66cc;">80.33</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// retorna 80.33% de 1000 como int (803)</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">get_percentage&lt;int, <span style="color: #993333;">float</span>, float&gt;<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1000</span>, <span style="color: #cc66cc;">80.33</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// retorna 80.33% de 1000 como float (803.3)</span></div></li></ol></pre>
<p><br/></p>
<p>Para deixar claro: "função&lt;<strong>tipo1</strong>, <strong>tipo2</strong>, <strong>tipoN</strong>&gt; (...);" corresponde a "template &lt;<strong>class tipo1</strong>, <strong>class tipo2</strong>, <strong>class tipoN</strong>...&gt; função(...);".</p>
<p>É possível utilizar os templates em classes também:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">template &lt;class T&gt;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">class my_class</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  private:</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    T attr;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  public:</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    my_class <span style="color: #66cc66;">&#40;</span>T value<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">        attr = value;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">my_class&lt;int&gt; object<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// instânciando</span></div></li></ol></pre>
<p><br/></p>
<p>Fiz uma explicação bem simples sobre o uso de templates, mas existem mais coisas que você deve aprender jovem Padawan. Recomendo uma lida aqui <a href="http://www.cplusplus.com/doc/tutorial/templates.html" target="_blank">cplusplus.com</a> e aqui <a href="http://www.google.com" target="_blank">Universal Knowledge Center About Everything</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2007/07/16/templates-em-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Como manter o FPS constante</title>
		<link>http://blog.stiod.com/2007/05/26/como-manter-o-fps-constante/</link>
		<comments>http://blog.stiod.com/2007/05/26/como-manter-o-fps-constante/#comments</comments>
		<pubDate>Sun, 27 May 2007 00:07:11 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.stiod.com.br/blog2/?p=18</guid>
		<description><![CDATA[Para quem está programando joguinhos simples em C/C++ usando a API do Windows vou dar (no bom sentido) uma dica sobre como manter o FPS constante e intenso (no bom sentido).
Sem um controle seu jogo irá processar os gráficos na velocidade do processador. Os computadores tem velocidades diferentes e as aplicações não tem um processamento [...]]]></description>
			<content:encoded><![CDATA[<p>Para quem está programando joguinhos simples em C/C++ usando a <a href="http://msdn2.microsoft.com/en-us/library/aa139672.aspx" target="_blank">API do Windows</a> vou dar (no bom sentido) uma dica sobre como manter o FPS constante e intenso (no bom sentido).</p>
<p>Sem um controle seu jogo irá processar os gráficos na velocidade do processador. Os computadores tem velocidades diferentes e as aplicações não tem um processamento constante e igual, seu jogo poderá rodar a 124 FPS, mas se mexer o mouse irá para 81 FPS, por exemplo.<br />
<span id="more-12"></span><br />
Antes de continuar você tem que conhecer o básico de como criar uma janela usando a Win32 API. Terá que usar também o <strong>PeekMessage</strong> ao invés do <strong>GetMessage</strong> no loop que pega os eventos (mensagens).</p>
<div style="position:relative; border: 2px #080 dashed; margin: 0px; padding-left: 10px; padding-right: 10px; background: #ffe; font-style: italic;"><a href="http://msdn2.microsoft.com/en-us/library/ms644943.aspx" target="_blank"><strong>PeekMessage</strong></a>: não aguarda por mensagens se a fila de mensagens (<a href="http://msdn2.microsoft.com/en-us/library/ms632590.aspx" target="_blank">Message Queue</a>) estiver vazia.</div>
<p><br/></p>
<p>Agora vamos a lógica da coisa, você tem que "pausar" esse loop em determinados intervalos, por exemplo, se quiser 60 FPS terá que pausar 60 vezes por segundo de modo que no final a soma dos intervalos atinja 1 segundo. Para pausar use o <strong>Sleep</strong>, porém ele trabalha em milisegundos, mas é só dividir 1000.0 (milisegundos) por 60.0 (FPS).</p>
<div style="position:relative; border: 2px #080 dashed; margin: 0px; padding-left: 10px; padding-right: 10px; background: #ffe; font-style: italic;"><a href="http://msdn2.microsoft.com/en-us/library/ms686298.aspx" target="_blank"><strong>Sleep</strong></a>: faz a thread suspender por um período de tempo (em milisegundos).</div>
<p><br/></p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">Sleep<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">16.66</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">// ou</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">Sleep<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1000.0</span>/<span style="color: #cc66cc;">60.0</span><span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p><br/></p>
<p>Pronto! Rápido e prático que nem miojo. <img src='http://blog.stiod.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>Agora se for um jogo pesado você terá que levar em contar o tempo de cada execução do loop. Use a função <strong>GetTickCount</strong> para capturar o tempo.</p>
<div style="position:relative; border: 2px #080 dashed; margin: 0px; padding-left: 10px; padding-right: 10px; background: #ffe; font-style: italic;"><a href="http://msdn2.microsoft.com/en-us/library/ms724408.aspx" target="_blank"><strong>GetTickCount</strong></a>: retornar o tempo em milisegundos (<em>DWORD</em>) desde que o sistema foi iniciado (zera quando atinge 49,7 dias ou quando tem um eclipse solar).</div>
<p><br/></p>
<p>A cada loop some 16.66 ao tempo de execução do loop anterior, subtraia pelo tempo atual e o resultado será o tempo que o loop deve aguardar (<strong>Sleep</strong>). Se o resultado for negativo então o loop não deve aguardar.</p>
<p>Código abaixo pode ser mais esclarecedor:</p>
<pre class="c"><ol><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">// ...</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #993333;">int</span> iSleepTime = <span style="color: #cc66cc;">0</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">BOOL bPeekMsgRes;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">DWORD lastTime = GetTickCount<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #b1b100;">while</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">// Main event loop</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">    bPeekMsgRes = PeekMessage<span style="color: #66cc66;">&#40;</span>&amp;Msg,</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">                              <span style="color: #000000; font-weight: bold;">NULL</span>,</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">                              <span style="color: #cc66cc;">0</span>,</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">                              <span style="color: #cc66cc;">0</span>,</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">                              PM_REMOVE<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>bPeekMsgRes<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>Msg.<span style="color: #202020;">message</span> == WM_QUIT<span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">           <span style="color: #000000; font-weight: bold;">break</span>; <span style="color: #808080; font-style: italic;">// Break main event loop</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       <span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">           TranslateMessage<span style="color: #66cc66;">&#40;</span>&amp;Msg<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">           DispatchMessage<span style="color: #66cc66;">&#40;</span>&amp;Msg<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #808080; font-style: italic;">/* ---- Main game processing ---- */</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #808080; font-style: italic;">// Corta, pica e fatia no jogo...</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #808080; font-style: italic;">/* ---- FPS control ---- */</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   lastTime += <span style="color: #cc66cc;">16.66</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   iSleepTime = lastTime - GetTickCount<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #b1b100;">if</span><span style="color: #66cc66;">&#40;</span>iSleepTime &gt; <span style="color: #cc66cc;">-1</span><span style="color: #66cc66;">&#41;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       <span style="color: #808080; font-style: italic;">// Normal</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       Sleep<span style="color: #66cc66;">&#40;</span>iSleepTime<span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       <span style="color: #808080; font-style: italic;">// Lento</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">       <a href="http://www.opengroup.org/onlinepubs/009695399/functions/printf.html"><span style="color: #000066;">printf</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;OMG! Tá lento isso hein?<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #66cc66;">&#41;</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">   <span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #66cc66;">&#125;</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">/* ---- Game Over ---- */</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color: #808080; font-style: italic;">// ...</span></div></li></ol></pre>
<p><br/></p>
<p><strong>obs</strong>: Tem um "printf" ali que só vai aparecer se a janela tiver um prompt. Você pode compilar sua aplicação/jogo/miojo para que seja exibido o prompt junto, não sei como se faz isso no VisualC++, mas no DevC++ (GCC) crie um projeto "Win32 Console" ou compile com "-mconsole".</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2007/05/26/como-manter-o-fps-constante/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extendendo Python com cTypes</title>
		<link>http://blog.stiod.com/2007/02/02/extendendo-python-com-ctypes/</link>
		<comments>http://blog.stiod.com/2007/02/02/extendendo-python-com-ctypes/#comments</comments>
		<pubDate>Fri, 02 Feb 2007 22:35:07 +0000</pubDate>
		<dc:creator>Rafael Sierra</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://www.stiod.com.br/blog2/?p=9</guid>
		<description><![CDATA[Esses dias tive que implementar algumas coisas em C, por dois motivos, primeiro eu queria comparar a velocidade da mesma aplicação em duas linguagens (Python e C) e segundo, já estava na hora de começar a usar C com Python  .
Os primeiros testes que fiz (com a ajuda do Gean) foi usando a documentação [...]]]></description>
			<content:encoded><![CDATA[<p>Esses dias tive que implementar algumas coisas em C, por dois motivos, primeiro eu queria comparar a velocidade da mesma aplicação em duas linguagens (Python e C) e segundo, já estava na hora de começar a usar C com Python <img src='http://blog.stiod.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p>Os primeiros testes que fiz (com a ajuda do Gean) foi usando a documentação oficial do Python que pode ser encontrada <a href="http://docs.python.org/ext/ext.html">aqui</a>. Foi relativamente fácil e não tive muitos (mais do que nenhum) problemas.</p>
<p>Porém a perfomance não era a esperada, então parti para outros testes, e um desses foi exatamente sobre a biblioteca <a href="http://starship.python.net/crew/theller/ctypes/">ctypes</a>. Atualmente ela é um pacote "third-part" (feito por terceiros), porém, será builtin na versão 2.5 <img src='http://blog.stiod.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<span id="more-7"></span><br />
Sua instalação é simples e seu uso mais ainda.</p>
<p>Então vamos aos códigos, nós vamos fazer a clássica função fatorial. Pra começar precisamos definir os arquivos:</p>
<ul>
<li><strong>teste_fatorial.py</strong> Arquivo que vai chamar a função em C</li>
<li><strong>fatorial.c</strong> Código que contém o algorítimo da função</li>
</ul>
<p>Aqui está a implementação dos arquivos:</p>
<p><strong>fatorial.c</strong><br />
[c]<br />
/*<br />
 * Pra compilar esse codigo como biblioteca usando o GCC execute:<br />
 * gcc -o fatorial.so -shared fatorial.c<br />
 */<br />
#include <stdio.h></p>
<p>int<br />
fatorial(int numero, int mult)<br />
{<br />
    if (numero == 1)<br />
    {<br />
        return mult;<br />
    }<br />
    else<br />
    {<br />
        return fatorial(--numero, mult*numero);<br />
    }</p>
<p>}<br />
[/c]</p>
<p><strong>teste_fatorial.py</strong><br />
[python]<br />
import ctypes</p>
<p># A biblioteca tem que estar no mesmo diretorio do teste_fatorial.py<br />
Fatorial = ctypes.CDLL("./fatorial.so")</p>
<p># Seta o retorno da funcao para inteiro<br />
Fatorial.fatorial.restype = ctypes.c_int</p>
<p># Imprime o resultado da funcao<br />
print Fatorial.fatorial(5, 1)<br />
[/python]</p>
<p>Como você pode ver, nenhuma alteração no código em C precisa ser feita, você pode importar qualquer modulo pré-compilado que já exista, como a libc, a libgd e muitas outras já existentes no Linux.</p>
<p>Depois de carregar uma biblioteca, é recomendável que você altere o restype das funções que você vai chamar, por exemplo, no exemplo do fatorial eu setei para c_int, pois isso é o que a função retorna, um inteiro. Essa e outras observações você encontra na <a href="http://starship.python.net/crew/theller/ctypes/tutorial.html">documentação do ctypes</a> e na <a href="http://docs.python.org/dev/lib/module-ctypes.html">página do Python</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2007/02/02/extendendo-python-com-ctypes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
