<?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; Windows</title>
	<atom:link href="http://blog.stiod.com/category/windows/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>Como extrair o conteúdo de um arquivo rpm?</title>
		<link>http://blog.stiod.com/2009/03/16/como-extrair-o-conteudo-de-um-arquivo-rpm/</link>
		<comments>http://blog.stiod.com/2009/03/16/como-extrair-o-conteudo-de-um-arquivo-rpm/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 01:16:13 +0000</pubDate>
		<dc:creator>Gabriel Verta</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Xapian]]></category>
		<category><![CDATA[extract]]></category>
		<category><![CDATA[rpm]]></category>
		<category><![CDATA[shell]]></category>

		<guid isPermaLink="false">http://blog.stiod.com/?p=306</guid>
		<description><![CDATA[O comando que extrai todo o conteudo de um arquivo rpm, criando as pastas que o rpm criaria a partir do diretório atual:
rpm2cpio arquivo.rpm &#124; cpio -idmv
  

Link sobre cpio
]]></description>
			<content:encoded><![CDATA[<p>O comando que extrai todo o conteudo de um arquivo rpm, criando as pastas que o rpm criaria a partir do diretório atual:</p>
<p><code>rpm2cpio arquivo.rpm | cpio -idmv</code><br />
 <img src='http://blog.stiod.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>
<a href="http://www.gnu.org/software/cpio/">Link sobre cpio</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2009/03/16/como-extrair-o-conteudo-de-um-arquivo-rpm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Postfix I</title>
		<link>http://blog.stiod.com/2009/01/07/postfix-i/</link>
		<comments>http://blog.stiod.com/2009/01/07/postfix-i/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 23:40:24 +0000</pubDate>
		<dc:creator>pathi</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://blog.stiod.com/?p=222</guid>
		<description><![CDATA[People,
Esses dias tive que estudar um pouco sobre Postfix para entender marromenos como que funciona um server de email. Então ai vai um passo-a-passo do que eu fiz para subir  esse servidor de email com Postfix usando o squirrelmail para testar os envios e recebimentos dos emails  
Usei Ubuntu Server (não gosto muito mas [...]]]></description>
			<content:encoded><![CDATA[<p>People,</p>
<p>Esses dias tive que estudar um pouco sobre Postfix para entender marromenos como que funciona um server de email. Então ai vai um passo-a-passo do que eu fiz para subir  esse servidor de email com Postfix usando o squirrelmail para testar os envios e recebimentos dos emails <img src='http://blog.stiod.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Usei Ubuntu Server (não gosto muito mas era o que eu tinha na mão) e gerenciador de pacote aptitude. O mesmo funciona com apt-get se preferir :-p</p>
<p>Primeiramente, vamos instalar os pacotes básicos na máquina. Esses pacotes não são necessariamente só do Postfix.</p>
<p><strong> # aptitude install openssh-server vim-full mutt nmap postfix</strong></p>
<p>Durante a instalação, provavelmente serão feitas algumas perguntas. Por enquanto, apenas dê ENTER para todas elas. Porque assim que a instalação terminar, iremos reconfigurar algumas opções e depois editar o arquivo de configuração direto.</p>
<p>Feita a instalação, vamos reconfigurar algumas opções básicas:</p>
<p><strong> # dpkg-reconfigure postfix</strong></p>
<p>Abaixo, segue um exemplo de configuração que foi definida:</p>
<p><em> =&gt; OK<br />
=&gt; Internet Site<br />
=&gt; dominio.com.br<br />
=&gt; (em branco)<br />
=&gt; $myhostname, localhost.$mydomain, $mydomain<br />
=&gt; yes<br />
=&gt; 127.0.0.0/8 192.168.1.0/24<br />
=&gt; yes<br />
=&gt; 0<br />
=&gt; +<br />
=&gt; all</em></p>
<p>Depois que definirmos todas essas configurações, então automaticamente o postfix será recarregado (reload) e reiniciado.<br />
Nesse server básico de Postfix, estou usando a mesma base de usuários comuns do sistema, como usuários que terão email no postfix. Lembrando que todos esses usuários comuns, são os que possuem ID maior que 1000 e estão dentro de /etc/passwd.</p>
<p>Para esse primeiro teste, vou adicionar um usuário novo no sistema:</p>
<p><strong> # adduser joao</strong></p>
<p>Como o postfix já está instalado e com uma pré-configuração, então vamos enviar alguns emails entre os usuários comuns do sistema. Para isso, vamos usar o telnet mesmo:</p>
<p><em> $ telnet localhost 25</em></p>
<p><em>HELO smtp.dominio.com.br<br />
MAIL From: user@dominio.com.br<br />
RCPT to: joao@dominio.com.br<br />
DATA<br />
Mensagem do email.<br />
.<br />
QUIT</em></p>
<p>Como estamos fazendo tudo na máquina local por enquanto, então usei um telnet localhost na porta 25. Na linha HELO como o próprio nome já fala, estou dando um "Olá" para o meu server de email e domínio. Na linha MAIL From estou avisando qual o usuário que irá enviar o email e na linha RCPT to está o usuário que irá receber o email. Para escrever a mensagem, chamamos o DATA e então basta escrever o que você quiser. Para finalizar a mensagem, basta dar um . único e ele entenderá como fim da mensagem. E para finalizar o telnet, basta dar um QUIT.<br />
É importante prestar atenção nas palavras e letras maiúsculas.</p>
<p>Quando enviarmos esse email para o joao@dominio.com.br, será criado um arquivo com o nome do usuário em /var/mail/.<br />
Por exemplo:</p>
<p><strong> # ls /var/mail</strong><br />
joao</p>
<p>Então para ler o email, pode-se dar um cat nesse arquivo, ou então usar uma ferramenta chamada mutt, que lê emails em linha de comando.</p>
<p><strong> # cat /var/mail/joao</strong><br />
ou<br />
<strong> # su joao<br />
$ mutt<br />
</strong><br />
Abaixo, segue a estrutura do arquivo /etc/hostname:<br />
<strong><br />
# cat /etc/hostname<br />
dominio.com.br</strong></p>
<p>Abaixo, segue a estrutura do arquivo /etc/hosts:</p>
<p><strong> # cat /etc/hosts</strong><br />
<em> 127.0.0.1 localhost<br />
127.0.1.1 dominio.com.br dominio.com.br<br />
IP.ex.ter.no dominio.com.br dominio.com.br</em></p>
<p>A estrutura desses arquivos é importante, porque dependendo dos casos, o hostname e o domínio tem que estar com o mesmo nome.</p>
<p>O arquivo de configuração do Postfix está localizado em /etc/postfix/main.cf.<br />
Abaixo vou colocar umas linhas básicas desse arquivo de configuração para analisar o conteúdo. Não vou explicar o que todas as linhas fazem, mas sites como o do próprio postfix explica o conteúdo de cada linha e muitas vezes cita exemplos =p</p>
<p><strong> # vim /etc/postfix/main.cf</strong><br />
<em> myhostname = IP.ex.ter.no.dominio.com.br<br />
mydomain = dominio.com.br<br />
alias_maps = hash:/etc/aliases<br />
alias_database = hash:/etc/aliases<br />
myorigin = /etc/mailname<br />
mydestination = $myhostname, localhost.$mydomain, $mydomain<br />
relayhost =<br />
relay_domains = $mydomain<br />
mynetworks = 127.0.0.0/8 192.168.1.0/24<br />
home_mailbox = Maildir/<br />
recipient_delimiter = +<br />
inet_interfaces = all<br />
inet_protocols = all<br />
mailbox_size_limit = 0</em></p>
<p>Vamos configurar os serviços de pop e imap. Para isso, será necessário instalar os seguintes pacotes:</p>
<p><strong> # aptitude install courier-pop courier-pop-ssl<br />
# aptitude install courier-imap courier-imap-ssl</strong></p>
<p>Quando instalarmoas esses pacotes, será criado um diretório courier dentro do /etc/ e dentro desse diretório, teremos diversos arquivos. Antesde editar os arquivos e fazer as alterações, aconselho renomear os arquivos originais:<br />
<strong><br />
# cd /etc/courier<br />
# mv imapd.pem imapd.pem.old<br />
# mv pop3d.pem pop3d.pem.old</strong></p>
<p>O próximo passo, é editar os arquivos imap.cnf e pop3d.cnf e alterar as informações necessárias. Por exemplo coloque em Country=BR, State=Sao Paulo e etc:</p>
<p><strong> # vim imapd.cnf<br />
# vim pop3d.cnf</strong></p>
<p>Quando os arquivos forem alterados, devemos devemos criar novamente os arquivos imapd.pem e pop3d.pem com os comandos:</p>
<p><strong> # mkimapdcert<br />
# mkpop3dcert</strong></p>
<p>O próximo passo agora é instalar o squirrelmail, que é uma ferramenta para testar o envio e recebimento de mensagens de email através de uma interface web mesmo. Se preferir, pode usar alguma outra ferramenta, como eu já tinha comentado antes:</p>
<p><strong> # aptitude install squirrelmail<br />
# aptitude install php5</strong></p>
<p>Continua... :-p</p>
<p>Links de Referências:</p>
<p><a href="http://www.postfix.org/documentation.html">http://www.postfix.org/documentation.html</a></p>
<p><a href="https://help.ubuntu.com/7.04/server/C/postfix.html">https://help.ubuntu.com/7.04/server/C/postfix.html</a></p>
<p><a href="http://virtual01.lncc.br/~licht/linux/servidores.postfix.arq.html">http://virtual01.lncc.br/~licht/linux/servidores.postfix.arq.html</a></p>
<p><a href="http://www.gdhpress.com.br/redeseservidores/leia/index.php?p=cap10-2">http://www.gdhpress.com.br/redeseservidores/leia/index.php?p=cap10-2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2009/01/07/postfix-i/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>Criando planilhas do Excel com o Delphi</title>
		<link>http://blog.stiod.com/2007/11/28/criando-planilhas-do-excel-com-o-delphi/</link>
		<comments>http://blog.stiod.com/2007/11/28/criando-planilhas-do-excel-com-o-delphi/#comments</comments>
		<pubDate>Wed, 28 Nov 2007 15:57:36 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://blog.stiod.com.br/?p=57</guid>
		<description><![CDATA[É sempre importante saber exportar dados para vários formatos, seja para XML, CSV ou até HTML. E quando o cliente quer algum tipo de documento “palpável” para ele analisar, como os relatórios?
No Delphi tem gente que gosta de usar o Quickreport, outras preferem (ou são obrigadas) a utilizar o Rave Report ou Crystal Reports. Mas [...]]]></description>
			<content:encoded><![CDATA[<p>É sempre importante saber exportar dados para vários formatos, seja para XML, CSV ou até HTML. E quando o cliente quer algum tipo de documento “palpável” para ele analisar, como os relatórios?<br />
No Delphi tem gente que gosta de usar o Quickreport, outras preferem (ou são obrigadas) a utilizar o Rave Report ou Crystal Reports. Mas hoje eu vou mostrar como criar um relatório ou exportar dados utilizando planilhas do Excel.<br />
<span id="more-47"></span><br />
Talvez você não precise criar relatórios em planilhas do Excel, mas vou contar um caso que ocorreu com um amigo meu...</p>
<p>Esse meu amigo estava fazendo um sisteminha em Delphi para rodar na versão japonesa do Windows XP. Mas a versão do Delphi dele não tinha Quickreport, só tinha o Rave Report, e o Rave Report não exibia caracteres japoneses. Como eu... digo, esse meu amigo, precisava de uma solução rapidamente, ele resolveu exportar os dados para o Excel. Assim resolveria o problema de exibição dos caracteres japoneses e o cliente teria um arquivo que é familiar a ele, tanto para somente visualizar quanto para imprimir os dados/relatório.</p>
<p>É mais complicado e lento gerar planilhas no Excel do que gerar relatórios no Rave Report, mas em compensação os dados exportados ficam melhor formatados e maleáveis.</p>
<p><strong>Passos:</strong><br />
<em>- Adicione a unit ExcelXP<br />
- Adicionar as variaveis globais<br />
- Instâncie os componentes no OnCreate<br />
- Adicione um botao no Form<br />
- Gerar a planilha no OnClick do botão<br />
- Liberar a memoria no OnClose</em></p>
<pre class="pascal"><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: #000000; font-weight: bold;">unit</span> Unit1;</div></li><li style="font-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: #000000; font-weight: bold;">interface</span></div></li><li style="font-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: #000000; font-weight: bold;">uses</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  Dialogs, StdCtrls, ExcelXP;</div></li><li style="font-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;">type</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  TForm1 = class<span style="color: #66cc66;">&#40;</span>TForm<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;">    Button1: TButton;</div></li><li style="font-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;">procedure</span> FormCreate<span style="color: #66cc66;">&#40;</span>Sender: TObject<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: #000000; font-weight: bold;">procedure</span> FormClose<span style="color: #66cc66;">&#40;</span>Sender: TObject; <span style="color: #b1b100;">var</span> Action: TCloseAction<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: #000000; font-weight: bold;">procedure</span> Button1Click<span style="color: #66cc66;">&#40;</span>Sender: TObject<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;">private</span></div></li><li style="font-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;">{ Private declarations }</span></div></li><li style="font-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;">public</span></div></li><li style="font-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;">{ Public declarations }</span></div></li><li style="font-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;">end</span>;</div></li><li style="font-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;">var</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  Form1: TForm1;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  LCID: <span style="color: #993333;">Integer</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelApplication1: TExcelApplication;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorkbook1: TExcelWorkbook;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1: TExcelWorksheet;</div></li><li style="font-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;">implementation</span></div></li><li style="font-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;">{$R *.dfm}</span></div></li><li style="font-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: #000000; font-weight: bold;">procedure</span> TForm1.<span style="color: #202020;">FormCreate</span><span style="color: #66cc66;">&#40;</span>Sender: TObject<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;">begin</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelApplication1 := TExcelApplication.<span style="color: #202020;">Create</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">nil</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;">  ExcelWorkbook1 := TExcelWorkbook.<span style="color: #202020;">Create</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">nil</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;">  ExcelWorksheet1 := TExcelWorksheet.<span style="color: #202020;">Create</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">nil</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;">end</span>;</div></li><li style="font-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: #000000; font-weight: bold;">procedure</span> TForm1.<span style="color: #202020;">FormClose</span><span style="color: #66cc66;">&#40;</span>Sender: TObject; <span style="color: #b1b100;">var</span> Action: TCloseAction<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;">begin</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Free</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorkbook1.<span style="color: #202020;">Free</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelApplication1.<span style="color: #202020;">Free</span>;</div></li><li style="font-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;">end</span>;</div></li><li style="font-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: #000000; font-weight: bold;">procedure</span> TForm1.<span style="color: #202020;">Button1Click</span><span style="color: #66cc66;">&#40;</span>Sender: TObject<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;">begin</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  LCID := GetUserDefaultLCID;</div></li><li style="font-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;">  ExcelApplication1.<span style="color: #202020;">DisplayAlerts</span><span style="color: #66cc66;">&#91;</span>LCID<span style="color: #66cc66;">&#93;</span> := <span style="color: #000000; font-weight: bold;">False</span>;</div></li><li style="font-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;">  ExcelApplication1.<span style="color: #202020;">Workbooks</span>.<span style="color: #202020;">Add</span><span style="color: #66cc66;">&#40;</span>EmptyParam, LCID<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;">  ExcelWorkbook1.<span style="color: #202020;">ConnectTo</span><span style="color: #66cc66;">&#40;</span>ExcelApplication1.<span style="color: #202020;">Workbooks</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> as _Workbook<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;">  ExcelWorksheet1.<span style="color: #202020;">ConnectTo</span><span style="color: #66cc66;">&#40;</span>ExcelWorkbook1.<span style="color: #202020;">Worksheets</span><span style="color: #66cc66;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">&#93;</span> as _Worksheet<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;">  ExcelWorksheet1.<span style="color: #202020;">Activate</span><span style="color: #66cc66;">&#40;</span>LCID<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;">  ExcelApplication1.<span style="color: #202020;">ScreenUpdating</span><span style="color: #66cc66;">&#91;</span>LCID<span style="color: #66cc66;">&#93;</span> := <span style="color: #000000; font-weight: bold;">true</span>;</div></li><li style="font-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;">// nome da planilha (que aparece na aba)</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #b1b100;">Name</span> := <span style="color: #ff0000;">'Relatório ou Exportação'</span>;</div></li><li style="font-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;">{ inserindo dados na planilha }</span></div></li><li style="font-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;">// colocando titulo na primeira celula da planilha</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A1'</span>, <span style="color: #ff0000;">'A1'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Título'</span>;</div></li><li style="font-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;">// unindo as células de A1 ate C1 para o titulo ocupar 3 colunas</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A1'</span>, <span style="color: #ff0000;">'C1'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Merge</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">True</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;">// formatando o titulo</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A1'</span>, <span style="color: #ff0000;">'C1'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Font</span>.<span style="color: #202020;">Bold</span> := <span style="color: #000000; font-weight: bold;">True</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A1'</span>, <span style="color: #ff0000;">'C1'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Font</span>.<span style="color: #202020;">Size</span> := <span style="color: #cc66cc;">16</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A1'</span>, <span style="color: #ff0000;">'C1'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Font</span>.<span style="color: #202020;">Color</span> := RGB<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">255</span>,<span style="color: #cc66cc;">0</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;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A1'</span>, <span style="color: #ff0000;">'C1'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">HorizontalAlignment</span> := xlCenter;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A1'</span>, <span style="color: #ff0000;">'C1'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">VerticalAlignment</span> := xlCenter;</div></li><li style="font-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;">// colocando os nomes dos campos na segunda linha</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A2'</span>, <span style="color: #ff0000;">'A2'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Campo1'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'B2'</span>, <span style="color: #ff0000;">'B2'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Campo2'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'C2'</span>, <span style="color: #ff0000;">'C2'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Campo3'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A2'</span>, <span style="color: #ff0000;">'C2'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Font</span>.<span style="color: #202020;">Bold</span> := <span style="color: #000000; font-weight: bold;">True</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A2'</span>, <span style="color: #ff0000;">'C2'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Font</span>.<span style="color: #202020;">Color</span> := RGB<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">0</span>,<span style="color: #cc66cc;">255</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;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A2'</span>, <span style="color: #ff0000;">'C2'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">HorizontalAlignment</span> := xlCenter;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A2'</span>, <span style="color: #ff0000;">'C2'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">VerticalAlignment</span> := xlCenter;</div></li><li style="font-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;">// colocando os valores</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A3'</span>, <span style="color: #ff0000;">'A3'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Valor1'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'B3'</span>, <span style="color: #ff0000;">'B3'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Valor2'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'C3'</span>, <span style="color: #ff0000;">'C3'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Valor3'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A4'</span>, <span style="color: #ff0000;">'A4'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Valor4'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'B4'</span>, <span style="color: #ff0000;">'B4'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Valor5'</span>;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'C4'</span>, <span style="color: #ff0000;">'C4'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Value2</span> := <span style="color: #ff0000;">'Valor6'</span>;</div></li><li style="font-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;">// colocando borda nas celulas dos valores</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A3'</span>, <span style="color: #ff0000;">'C4'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">Borders</span>.<span style="color: #202020;">Weight</span> := xlThin;</div></li><li style="font-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;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A3'</span>, <span style="color: #ff0000;">'C4'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">HorizontalAlignment</span> := xlCenter;</div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Range</span><span style="color: #66cc66;">&#91;</span><span style="color: #ff0000;">'A3'</span>, <span style="color: #ff0000;">'C4'</span><span style="color: #66cc66;">&#93;</span>.<span style="color: #202020;">VerticalAlignment</span> := xlCenter;</div></li><li style="font-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;">{ formatando a pagina de impressão }</span></div></li><li style="font-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;">// ajusta o tamanho das colunas</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">Cells</span>.<span style="color: #202020;">EntireColumn</span>.<span style="color: #202020;">AutoFit</span>;</div></li><li style="font-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;">// define borda de impressao com cerca de 1cm</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">BottomMargin</span> := <span style="color: #cc66cc;">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;">  ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">LeftMargin</span> := <span style="color: #cc66cc;">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;">  ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">RightMargin</span> := <span style="color: #cc66cc;">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;">  ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">TopMargin</span> := <span style="color: #cc66cc;">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;">&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;">// deixa a planilha no centro da pagina horizontalmente</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">CenterHorizontally</span> := <span style="color: #000000; font-weight: bold;">True</span>;</div></li><li style="font-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;">// imprime o numero da pagina no rodapé</span></div></li><li style="font-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;">// '&amp;P' e o codigo para numero de pagina</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">CenterFooter</span> := <span style="color: #ff0000;">'&amp;P'</span>;</div></li><li style="font-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 o programa do Excel com a planilha criada</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">  ExcelApplication1.<span style="color: #202020;">Visible</span><span style="color: #66cc66;">&#91;</span>LCID<span style="color: #66cc66;">&#93;</span> := <span style="color: #000000; font-weight: bold;">True</span>;</div></li><li style="font-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;">end</span>;</div></li><li style="font-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;">end</span>.</div></li></ol></pre>
<p>E este é o resultado final:<br />
<a href='http://web.stiod.com/wp-content/uploads/2007/11/excel_celulas1.jpg' title='Células do Excel'><img src='http://web.stiod.com/wp-content/uploads/2007/11/excel_celulas1.jpg' alt='Células do Excel' /></a></p>
<p>Enquanto os objetos não forem destruídos o Excel estará aberto na memória, por isso tem uns "Frees" no OnClose do Form. Aqui tem outro comandos que podem ser usados:</p>
<pre class="pascal"><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;">// abre o PrintPreview (use depois do &quot;ExcelApplication1.Visible[LCID] := True;&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;">ExcelWorksheet1.<span style="color: #202020;">PrintPreview</span>;</div></li><li style="font-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;">// folha na horizontal</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">Orientation</span> := xlLandscape;</div></li><li style="font-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;">// impressao em preto e branco</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">ExcelWorksheet1.<span style="color: #202020;">PageSetup</span>.<span style="color: #202020;">BlackAndWhite</span> := <span style="color: #000000; font-weight: bold;">True</span>;</div></li><li style="font-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;">// Salva a planilha</span></div></li><li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;"><div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">ExcelWorksheet1.<span style="color: #202020;">SaveAs</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'c:<span style="color: #000099; font-weight: bold;">\c</span>aminho<span style="color: #000099; font-weight: bold;">\o</span>nde<span style="color: #000099; font-weight: bold;">\v</span>oce<span style="color: #000099; font-weight: bold;">\q</span>uer<span style="color: #000099; font-weight: bold;">\s</span>alvar<span style="color: #000099; font-weight: bold;">\p</span>lanilha.xls'</span><span style="color: #66cc66;">&#41;</span>;</div></li></ol></pre>
<p>Não dei muitos detalhes sobre os componentes utilizados, mas acho que já deve ajudar bastante pra procurar o resto <img src='http://blog.stiod.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2007/11/28/criando-planilhas-do-excel-com-o-delphi/feed/</wfw:commentRss>
		<slash:comments>13</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>WebCam no Python</title>
		<link>http://blog.stiod.com/2007/05/31/webcam-no-python/</link>
		<comments>http://blog.stiod.com/2007/05/31/webcam-no-python/#comments</comments>
		<pubDate>Thu, 31 May 2007 20:59:44 +0000</pubDate>
		<dc:creator>Yoshio Iwamoto</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.stiod.com.br/blog2/?p=19</guid>
		<description><![CDATA[É incrível como é fácil fazer certas coisas no Python que em outras linguagens seria algo tenebroso e macabro. Uma delas é a captura de vídeo usando uma simples WebCam USB.

Primeiro você precisa do módulo VideoCapture. E só.
Bom, só isso não porque o código não se escreve sozinho... (hehe)
[python]
from VideoCapture import Device
# Aqui sua WebCam [...]]]></description>
			<content:encoded><![CDATA[<p>É incrível como é fácil fazer certas coisas no Python que em outras linguagens seria algo tenebroso e macabro. Uma delas é a captura de vídeo usando uma simples WebCam USB.<br />
<span id="more-13"></span><br />
Primeiro você precisa do módulo <a href="http://videocapture.sourceforge.net/" target="_blank">VideoCapture</a>. E só.</p>
<p>Bom, só isso não porque o código não se escreve sozinho... (hehe)<br />
[python]<br />
from VideoCapture import Device</p>
<p># Aqui sua WebCam é ativada<br />
cam = Device()</p>
<p># Salva no diretório atual a imagem capturada deste instante<br />
cam.saveSnapshot('image.jpg')<br />
[/python]</p>
<p>Você também pode trabalhar com as imagens (<a href="http://www.pythonware.com/downloads/index.htm" target="_blank" title="Python Imaging Library">PIL</a>) diretamente:<br />
[python]<br />
from VideoCapture import Device</p>
<p>cam = Device()</p>
<p># Retorna uma imagem PIL<br />
im = cam.getImage()</p>
<p>width, height = im.size<br />
red, green, blue = im.getpixel((x, y))<br />
[/python]</p>
<p>Certas WebCams precisam "aquecer" antes que a imagem apareça limpa na tela, se for seu/meu caso é só colocar um delay depois de instanciar a classe Device:<br />
[python]<br />
from time import sleep<br />
from VideoCapture import Device</p>
<p>cam = Device()<br />
# Aquecendo (Oê!)<br />
sleep(4)<br />
[/python]</p>
<p>Agora vem a má notícia... Infelizmente o módulo VideoCapture só funciona no Windows.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.stiod.com/2007/05/31/webcam-no-python/feed/</wfw:commentRss>
		<slash:comments>9</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>
	</channel>
</rss>
