Trabalhando com sockets TCP em Java

De MediaWiki do Campus São José
Ir para navegação Ir para pesquisar
A versão imprimível não é mais suportada e pode ter erros de renderização. Atualize os favoritos do seu navegador e use a função de impressão padrão do navegador.

Servidor que atende um único cliente

Um exemplo bem simples de como usar sockets TCP em Java. O servidor está apto a atender um único cliente. Tanto o cliente quanto o servidor poderão enviar mensagens texto um para o outro.

Servidor.java

package tcp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Emerson Ribeiro de Mello
 */
public class Servidor {

    public void iniciar(int porta) {
        ObjectOutputStream saida;
        ObjectInputStream entrada;
        boolean sair = false;
        String mensagem = "";

        try {
            // criando um socket para ouvir na porta e com uma fila de tamanho 10
            ServerSocket servidor = new ServerSocket(porta, 10);
            Socket conexao;
            while (!sair) {
                System.out.println("Ouvindo na porta: " + porta);
                
                //ficarah bloqueado aqui ate' alguem cliente se conectar
                conexao = servidor.accept();

                System.out.println("Conexao estabelecida com: " + conexao.getInetAddress().getHostAddress());

                //obtendo os fluxos de entrada e de saida
                saida = new ObjectOutputStream(conexao.getOutputStream());
                entrada = new ObjectInputStream(conexao.getInputStream());
                
                //enviando a mensagem abaixo ao cliente
                saida.writeObject("Conexao estabelecida com sucesso...\n");

                do {//fica aqui ate' o cliente enviar a mensagem FIM
                    try {
                        //obtendo a mensagem enviada pelo cliente
                        mensagem = (String) entrada.readObject();
                        System.out.println("Cliente>> " + mensagem);
                        saida.writeObject(mensagem);
                    } catch (IOException iOException) {
                        System.err.println("erro: " + iOException.toString());
                    }
                } while (!mensagem.equals("FIM"));

                System.out.println("Conexao encerrada pelo cliente");
                sair = true;
                saida.close();
                entrada.close();
                conexao.close();

            }

        } catch (Exception e) {
            System.err.println("Erro: " + e.toString());
        }
    }

    public static void main(String[] args) {
        int porta = -1;

        //verificando se foi informado 1 argumento de linha de comando
        if (args.length < 1) {
            System.err.println("Uso: java tcp.Servidor <porta>");
            System.exit(1);
        }

        try { // para garantir que somente inteiros serao atribuidos a porta

            porta = Integer.parseInt(args[0]);

        } catch (Exception e) {
            System.err.println("Erro: " + e.toString());
            System.exit(1);
        }

        if (porta < 1024) {
            System.err.println("A porta deve ser maior que 1024.");
            System.exit(1);
        }

        Servidor s = new Servidor();
        s.iniciar(porta);
    }
}

Cliente.java

package tcp;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 *
 * @author Emerson Ribeiro de Mello
 */
public class Cliente {

    public void iniciar(String endereco, int porta) {
        ObjectOutputStream saida;
        ObjectInputStream entrada;
        Socket conexao;
        Scanner ler = new Scanner(System.in);
        String mensagem = "";
        try {
            conexao = new Socket(endereco, porta);
            System.out.println("Conectado ao servidor " + endereco + ", na porta: " + porta);
            System.out.println("Digite: FIM para encerrar a conexao");

            // ligando as conexoes de saida e de entrada
            saida = new ObjectOutputStream(conexao.getOutputStream());
            saida.flush();
            entrada = new ObjectInputStream(conexao.getInputStream());

            //lendo a mensagem enviada pelo servidor
            mensagem = (String) entrada.readObject();
            System.out.println("Servidor>> "+mensagem);

            do {
                System.out.print("..: ");
                mensagem = ler.nextLine();
                saida.writeObject(mensagem);
                saida.flush();
                //lendo a mensagem enviada pelo servidor
                mensagem = (String) entrada.readObject();
                System.out.println("Servidor>> "+mensagem);
            } while (!mensagem.equals("FIM"));

            saida.close();
            entrada.close();
            conexao.close();

        } catch (Exception e) {
            System.err.println("erro: " + e.toString());
        }

    }

    public static void main(String[] args) {
        if (args.length < 2) {
            System.err.println("Uso: java tcp.Cliente <endereco-IP> <porta>");
            System.exit(1);
        }

        Cliente c = new Cliente();
        c.iniciar(args[0], Integer.parseInt(args[1]));
    }
}

Bate papo em modo gráfico

O exemplo a seguir faz parte do livro Java Como Programar e ilustra o uso de sockets TCP em Java para conceber uma aplicação gráfica para bate papo.

Server.java

// Fig. 21.3: Server.java
// Set up a Server that will receive a connection
// from a client, send a string to the client,
// and close the connection.

package Sockets;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame {
   private JTextField enter;
   private JTextArea display;
   ObjectOutputStream output;
   ObjectInputStream input;

   public Server(){
      super( "Server" );
      Container c = getContentPane();
      enter = new JTextField();
      enter.setEnabled( false );
      enter.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e ){
               sendData( e.getActionCommand() );
            }
         }
      );

      c.add( enter, BorderLayout.NORTH );
      display = new JTextArea();
      c.add( new JScrollPane( display ),
             BorderLayout.CENTER );
      setSize( 300, 150 );
      show();
   }

   public void runServer(){
      ServerSocket server;
      Socket connection;
      int counter = 1;
      try {
         // Step 1: Create a ServerSocket.
         server = new ServerSocket( 5050, 100 );
         while ( true ) {
            // Step 2: Wait for a connection.
            display.setText( "Waiting for connection\n" );
            connection = server.accept();
            display.append( "Connection " + counter + " received from: " +
               connection.getInetAddress().getHostName() );

            // Step 3: Get input and output streams.
            output = new ObjectOutputStream(connection.getOutputStream() );
            output.flush();

            input = new ObjectInputStream(connection.getInputStream() );
            display.append( "\nGot I/O streams\n" );

            // Step 4: Process connection.
            String message = "SERVER>>> Connection successful";
            output.writeObject( message );
            output.flush();
            enter.setEnabled( true );

            do {
               try {
                  message = (String) input.readObject();
                  display.append( "\n" + message );
                  display.setCaretPosition(display.getText().length() );
               }catch ( ClassNotFoundException cnfex ) {
                  display.append("\nUnknown object type received" );
               }
            } while ( !message.equals( "CLIENT>>> TERMINATE" ) );

            // Step 5: Close connection.
            display.append( "\nUser terminated connection" );
            enter.setEnabled( false );
            output.close();
            input.close();
            connection.close();
            ++counter;
         }
      }catch ( EOFException eof ) {
         System.out.println( "Client terminated connection" );
      }catch ( IOException io ) {
         io.printStackTrace();
      }
   }

   private void sendData( String s ){
      try {
         output.writeObject( "SERVER>>> " + s );
         output.flush();
         display.append( "\nSERVER>>>" + s );
      }catch ( IOException cnfex ) {
         display.append("\nError writing object" );
      }
   }

   public static void main( String args[] ){
      Server app = new Server();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e ){
               System.exit( 0 );
            }
         }
      );

      app.runServer();
   }
}

/**************************************************************************
 * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/

Client.java

// Fig. 21.4: Client.java
// Set up a Client that will read information sent
// from a Server and display the information.
package Sockets;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client extends JFrame {
   private JTextField enter;
   private JTextArea display;
   ObjectOutputStream output;
   ObjectInputStream input;
   String message = "";

   public Client(){
      super( "Client" );
      Container c = getContentPane();
      enter = new JTextField();
      enter.setEnabled( false );
      enter.addActionListener(
         new ActionListener() {
            public void actionPerformed( ActionEvent e ){
               sendData( e.getActionCommand() );
            }
         }
      );

      c.add( enter, BorderLayout.NORTH );
      display = new JTextArea();
      c.add( new JScrollPane( display ), BorderLayout.CENTER );
      setSize( 300, 150 );
      show();
   }

   public void runClient(){
      Socket client;
      try {
         // Step 1: Create a Socket to make connection.
         display.setText( "Attempting connection\n" );
         client = new Socket(InetAddress.getByName( "127.0.0.1" ), 5050 );

         display.append( "Connected to: " + client.getInetAddress().getHostName() );

         // Step 2: Get the input and output streams.
         output = new ObjectOutputStream(client.getOutputStream() );
         output.flush();
         input = new ObjectInputStream(client.getInputStream() );
         display.append( "\nGot I/O streams\n" );

         // Step 3: Process connection.
         enter.setEnabled( true );

         do {
            try {
               message = (String) input.readObject();
               display.append( "\n" + message );
               display.setCaretPosition(display.getText().length() );
            }catch ( ClassNotFoundException cnfex ) {
               display.append("\nUnknown object type received" );
            }
         } while ( !message.equals( "SERVER>>> TERMINATE" ) );

         // Step 4: Close connection.
         display.append( "Closing connection.\n" );
         output.close();
         input.close();
         client.close();
      }catch ( EOFException eof ) {
         System.out.println( "Server terminated connection" );
      }catch ( IOException e ) {
         e.printStackTrace();
      }
   }

   private void sendData( String s ){
      try {
         message = s;
         output.writeObject( "CLIENT>>> " + s );
         output.flush();
         display.append( "\nCLIENT>>>" + s );
      }catch ( IOException cnfex ) {
         display.append("\nError writing object" );
      }
   }

   public static void main( String args[] ){
      Client app = new Client();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e ){
               System.exit( 0 );
            }
         }
      );

      app.runClient();
   }
}

/**************************************************************************
 * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 *************************************************************************/


Página principal da disciplina de POO