Demo Blog

Multi Thread Socket em Java

por Anônimo

Aqui ensino como fazer uma comunicação entre um cliente e um servidor utilizando sockets em Java, o código esta bem comentado, espero que ajude ! =]


import java.net.*;
import java.io.*;

/**
 *
 * @author Valter
 */
public class Servidor implements Runnable {

    ServerSocket ss;

    public Servidor(int porta) throws Exception {

        // informando em qual porta o servidor estará ouvindo
        ss = new ServerSocket(porta);

        // criando uma nova thread e já estou inicializando ela
        new Thread(this).start();

        // mensagem iniicial
        System.out.println("Servidor ouvindo na porta:" + porta);

    }

    public void run() {
        try {
            while (true) {
                // aceitando a conexão com o cliente e inicializando a outra thread
                new TrataCliente(ss.accept()).start();
                System.out.println("Mais um cliente atendido!");

            }

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static void main(String[] args) {
        try {
            new Servidor(1024);

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

class TrataCliente extends Thread {

    private Socket client;

    public TrataCliente(Socket s) {
        client = s;
    }

    public void run() {
        try {
            // aqui vai a sua comunicacao com o cliente
            ObjectInputStream oi = new ObjectInputStream(client.getInputStream());

            // exibindo na tela o que recebemos do nosso cliente
            System.out.println("Chegou isso:" + oi.readObject());

            client.close();

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

O nosso cliente
import java.net.*;
import java.io.*;

/**
 *
 * @author Valter
 */
public class Cliente extends Thread {

    // aqui no nosso caso será o 'localhost' que o ip da própria maquina aonde você executará
    private String server;
    // neste caso utilizaremos a partir da porta 1024, sendo que menor são para o Sistema Operacional
    private int porta;
    // aqui será a nossa string que será enviada para o servidor e ficará repetindo diversas vezes
    private String texto;

    public Cliente(String server, int porta) {
        try{
        // preparando o buffer para ler a stream (no caso o teclado)
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        
        // estamos lendo a stream que esta vindo do usuário
        texto = inFromUser.readLine();

        }catch(Exception e){
            e.printStackTrace();
        }

        this.server = server;
        this.porta = porta;
    }

    public static void main(String[] args) {
        try {

            // inicializando quem será nosso servidor (nossa máquina)
            String server = "localhost";
            
            // o numero da porta
            int porta = 1024;

            // o numero máx de clientes que podem ser atendidos, mais que isso começaremos a ter muitas exceções
            int numeroDeClientes = 10;

            for (int i = 0; i < numeroDeClientes; i++) {

                // criando um novo cliente para nosso servidor
                new Cliente(server, porta).start();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {

            while (true) {

                // abrindo uma porta para fazermos a comunicação entre nosso cliente e nosso servidor
                Socket s = new Socket(server, porta);

                // instaciando para enviarmos ao nosso servidor o que digitamos no cliente
                ObjectOutputStream oo = new ObjectOutputStream(s.getOutputStream());

                // informando aonde estamos conectados
                System.out.println("Conectado a " + server + ":" + porta);

                // enviando ao nosso servidor a nossa string
                oo.writeObject(texto);

                //fechando a nossa conexão
                s.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Lembrando que para rodar o programa, vá no prompt , localize a pasta onde esta o servidor.java e o cliente.java, então faça o comando:
javac servidor.java
depois
java cliente.java
para testar, em uma janela do prompt você digita:
java servidor
em outra janela, voce digita:
java cliente
então no cliente você colocaria :
11111111111111 (por exemplo)
ao abrir outra janela, coloque:
22222222222222 (por exemplo)
no servidor você verá que fica alternando entre 1111111111 e 222222222222, e assim vai,rs.
Bem eh isso galera, um forte abraço.
2 comentários mais...

Em memória, Steve Jobs.

por Anônimo

wallpaper-1379747

Descanse em paz meu amigo, a verdadeira ‘descoberta’ virá agora, um forte abraço aonde estiver.

0 comentários mais...

Aos 29 anos ouvindo a própria voz pela primeira vez

por Anônimo

Esta garota nasceu surda e neste vídeo ela tem seu aparelho auditivo ligado pela primeira vez. Impossível não sentir a emoção dela ao ouvir pela primeira vez.

São momentos como este que nos faz perceber como podemos fazer o bem ao nosso próximo, acreditar em um ideal, acreditar que podemos fazer a vida de alguém diferente, melhorá-la.

Muito emocionante o vídeo.

Parabéns ao criadores deste projeto e todos os envolvidos, só fazem me orgulhar da área que tanto estudo.

=)

0 comentários mais...

Firefox 7: mais rápido e menos consumo de memória

por Anônimo

 

Seis semanas depois de lançar o Firefox 6, a Mozilla lança a versão 7 do seu navegador, disposta a mergulhar de vez na guerra de navegadores. O destaque desta nova versão é uma melhor gestão da memória, o que causará uma maior rapidez ao navegar.

Firefox 7Segundo explica a Mozilla em seu blog, os usuários irão notar que o navegador “é mais rápido na abertura de novas abas, ao clicar em itens do menu e em botões das paginas dos sites.” Outra das melhorias adicionadas é a sincronização automática de bookmarks e alterações de senha, graças ao Firefox Sync. Por outro lado, o prefixo “http://” nas URLs aparecerá oculto a partir de agora, como no Chrome, e se adicionou um novo sistema de feedback (Telemetry), pelo qual os dados de desempenho serão enviados para a Mozilla. Os usuários que desejarem poderão optar pela ferramenta, para contribuir com a melhoria do navegador. Trata-se de uma ferramenta construída sobre os princípios de privacidade da Mozilla, que permite aos usuários mandar informações sobre sua navegação web de forma anônima e segura.

Também foram corrigidos mais de 1200 problemas de segurança e estabilidade, foi atualizado o protocolo WebSocket a partir da versão 7 e também na versão 8 e foi acrescentado o suporte para MathML, Web Timing  e “text-overflow: ellipsis”. Você pode baixar o Firefox 7 para o Windows , Mac e Linux e começar a experimentar todas essas novidades.

Fonte

Eu usava mto o firefox, mas ai começou com essas novas versões e as extensões não eram compatíveis, ai fui parando de usar e usando só o Chrome atualmente.

Uma coisa é certa, não adianta a Mozilla querer acelerar no desenvolvimento do Firefox se não fizer uma base sólida a todos os seus usuários antigos, o problema que citei com as extensões é um exemplo.

0 comentários mais...

Pernas robóticas ensinam pacientes a voltar a andar

por Anônimo

O aparelho, desenvolvido por engenheiros holandeses, é destinado a vítimas de AVC que perderam a habilidade de caminhar

por Redação Galileu

Editora Globo

Cientistas da Universidade de Twente, na Holanda, estão usando pernas robóticas para ajudar as vítimas de derrame cerebral a aprender a andar novamente. O exoesqueleto, nomeado de LOPES, detecta em tempo real o que o paciente está fazendo de errado e responde dando força e apoio à área necessária.
O aparelho não é móvel, mas apóia a pessoa enquanto ela anda por uma esteira. Os engenheiros que o desenvolveram acreditam que, além de mostrar fisicamente aos pacientes como caminhar corretamente, a máquina pode também ajudá-los a desenvolver os sinais cerebrais necessários para a melhoria do movimento.
A expectativa é de que uma versão comercial da máquina esteja disponível para compra em 2012. Assista ao LOPES em ação no vídeo abaixo:

Fonte

0 comentários mais...

Configurar Gmail IMAP no Outlook 2010

por Anônimo

 

OutlookGmail is one of the email services which supports IMAP feature which enables to send and receive emails from Outlook without any ads. Besides one use Outlook for all the business mails and now you can also add your personal gmail account along with it. The advantage of having setup this using IMAP is that when you read a mail or delete a mail, it is synchronized with both the web version of Gmail and the Outlook.

There are lots of features which are different in the new Outlook from Office 2010 than Outlook2007 which makes it even more desirable to use Outlook for your Gmail.

Having said that, now lets see How to Setup Gmail IMAP in Outlook 2010?

Before you can start using Gmail IMAP in Outlook, we need to enable IMAP in Gmail settings.

In Gmail, go to Settings -> Forwarding and POP/IMAP –> Make sure Enable IMAP is checked and click on Save Changes if you made any.

If you are starting the Microsoft outlook 2010 for the first time, you will be seeing the following startup screen, just click Next and choose Yes in the next screen where they askwould you like to configure an email account?

outlook2010-startup

account-configuration-2

Note: If you already have another email account or if you have chosen No in the earlier case and has already gone through the initial outlook startup settings before, follow this screenshot else continue to the next one.

Click the Office button on the top left corner and go to the Office Backstage. Under Info –>Account Information –> Click Account Settings and Click on Add Account.

image

On the Add New Account screen, just choose Manually configure server settings or additional server types and click Next.

add-new-account-office2010-3

Choose Internet E-mail, connect to POP or IMAP server to send and receive e-mail messages and click Next.

add-new-account-office2010-4

Here give the User information, enter your Name, your full email address including @gmail.com or your @custom-mail.com.

Under Server information,

Account Type – IMAP

Incoming mail server – imap.gmail.com

Outgoing mail server (SMTP) – smtp.gmail.com

Also enter the logon information, enter your user name in full and enter the password.

NOTE: Now don’t click Next yet, click on More settings above it.

add-new-account-office2010-5

In the Internet email settings, go to Advanced Tab to change the server port numbers.

Change Incoming server (IMAP) to 993 and use SSL as the encrypted connection.

Change outgoing server (SMTP) to 587 and use TLS as the encrypted connection.

add-advanced-settings-outlook2010-6

Now go to Outgoing server tab and check My outgoing server (SMTP) requires authenticationand choose Use same settings as my incoming mail server.

outgoing-server-details-outlook-2010-7

Now you should be taken back to the Add new account screen, click on Test Account Settingsand see if everything works without any errors. If there are any errors go back to all the settings and recheck if you have entered correctly.

test-account-settings-outlook-2010-8

Click Ok and Finish.

finish-setup-outlook2010-9

Now you will be taken to the main Outlook window and on the left sidebar a new set of folders will be created to synchronize with the Gmail account. It will also include Drafts, Sent Mail, Spam, Starred, Trash and all other mails synchronized.

image

Note: If you have a huge Gmail account already, then it will take sometime to download all your email contents from the web server.

Setting up the Sent Items Folder

When you send a mail for the first time, it will ask you where to store the sent mails. Make sure you DO NOT SET the sent mail from Gmail. When you send a mail through outlook, it goes to the gmail server and it saves the sent mails automatically to the sent mail folder. Now if you try to save it again in the sent mail, it will create duplicate copies of the sent mails. So use the Local Folder. See my other post on Choosing the Sent Items Folder while using Gmail in Outlook

sent-items-folder-10

Setting up the Deleted Items Folder

In gmail, you can either archive a mail or delete a mail. When you archive a mail, they are removed from the Inbox but they still remain in All Mails folder but when you delete they are moved to the trash mail folder and eventually deleted permanently after 30 days.

Likewise, you can set the action to move the mails to trash folder when you delete them.

deleted-items-folder-12

deleted-items-folder-13

If you want to archive a mail but not delete it, I usually have a folder called arhive and move the mails there so that my inbox remains clean and concise.

Folders and Labels

Outlook Folders are equivalent of labels in gmail. If you add a mail to two labels it will be present in both the folders.

Also read How you can manage Gmail better in Outlook and also reduce Gmail memory space in outlook.

Fonte

3 comentários mais...

Procura algo?

Busque aqui para achar algo no site:

Caso não tenha achado o que procurava, me envie um email para que eu possa cuidar disso para você.

Paperblog :Os melhores artigos dos blogs