Alguem sabe como devo desenvolver esta aplicação?

4 respostas
F

Estou tendo dificuldade para desenvolver uma aplicação em java usando cliente/Servidor onde o servidor tem que ser iterativo e a comunicação usa sock_stream.

O cliente irá tentar a conexão
Se nao espera
sim - Lê dimensão da matriz
Lê colunas
Lê vetor
Envia arquivo.dat
Espera resposta
Recebe resposta(.dat)
Desconecta
Mostra respsota(
.dat)
Apaga ( Resp.dat)
fim se

Já o servidor
associa endereço - BIND()
Espera conexão - Listen()
Aceita a conexão- Accept()
Recebe arquivo(*.dat)
Chamará outro programa que no caso será o matlab 6 que será usado para realizar a programação lineare apos executado e este enviará a (Resp.dat)
Espera a criaçao do arquivo
envia resposta
close()- apaga arquivos (Dados.dat, resp.dat)

Estou tendo muito dificuldade e estou precisando muito da ajuda de quem estiver interessado em ajudar. E qualquer dúvida também estarei disponivel para eventual duvidas posteriores.

Obrigado,

Fernando o Fegutao

4 Respostas

M

esse teu servidor precisa ouvir varios clientes ao mesmo tempo? Tenho um exemplo bem básico aqui que usa Threads, acho que serve pra algum começo…

F

Caro amigo como havia dito antes o servidor é iterativo ou seja deve ouvir apenas um cliente por vez. Mas se estiver algum exemplo você pode me enviar pois estou precisando muito. Acho que o que você me falou dá para fazer algumas modificções.

Valeu amigo,

fegutao

Aguardo sua resposta

M

não achei oq havia dito, mas tenho essas duas classes, uma servidor e outra cliente, que se enviam Strings… veja se consegue aproveitar algo…

Server.java

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

public class Server extends JFrame {

   private JTextField enterField;
   private JTextArea displayArea;
   private ObjectOutputStream output;
   private ObjectInputStream input;
   private ServerSocket server;
   private Socket connection;
   private int counter = 1;
	
   public Server()
   {
      super( "Server" );

      Container box = getContentPane();
		
      enterField = new JTextField();
      enterField.setEnabled( false );
		
      enterField.addActionListener(
		
         new ActionListener() {
			
            public void actionPerformed( ActionEvent e )
            {
               sendData( e.getActionCommand() );
               enterField.setText( "" );			
            }
         }
      );
		
      box.add( enterField, BorderLayout.NORTH );
		
      displayArea = new JTextArea();
      box.add( new JScrollPane( displayArea ), BorderLayout.CENTER );
		
      setSize( 300, 150 );
      setVisible( true );
   }
	
   public void runServer()
   {
      try {

         // Etapa 1: cria um ServerSocket
         server = new ServerSocket( 6000, 10 );
			
         while ( true ) {
		
            // Etapa 2: espera uma conexao
            waitForConnection();
				
            // Etapa 3: obtem fluxos de entrada e saida
            getStreams();
				
            // Etapa 4: processa a conexao
            processConnection();
				
            // Etapa 5: fecha a conexao
            closeConnection();
				
            ++counter;
         }
      } 
		
      catch ( EOFException e1 )
      {
         System.out.println( "Cliente fechou a conexao" );
      }
			
      catch ( IOException e2 )
      {
         e2.printStackTrace();
      }
   }

   private void waitForConnection() throws IOException
   {
      displayArea.setText( "Esperando pela conexao...\n" );
		
      connection = server.accept();
		
      displayArea.append( "Conexao " + counter + " recebida de: " + connection.getInetAddress().getHostName() );
   }
	
   private void getStreams() throws IOException
   {
      output = new ObjectOutputStream( connection.getOutputStream() );
		
      output.flush();

      input = new ObjectInputStream( connection.getInputStream() );
		
      displayArea.append( "\nGot I/O streams\n" );
   }
	
   private void processConnection() throws IOException
   {
      String message = "SERVER> conexao feita";
      output.writeObject( message );
      output.flush();
		
      enterField.setEnabled( true );
		
      do {
		
         try {

            message = ( String ) input.readObject();
            displayArea.append( "\n" + message );
            displayArea.setCaretPosition( displayArea.getText().length() );
         }

         catch ( ClassNotFoundException classNotFount )
         {
            displayArea.append( "\n**Tipo de objeto recebido desconhecido**" );
         }		
		
      } while ( !message.equals( "CLIENT> exit" ) );
   
   }

   private void closeConnection() throws IOException
   {
      displayArea.append( "\nUsuario terminou a conexao" );
      enterField.setEnabled( false );
      output.close();
      input.close();
      connection.close();
   }

   private void sendData( String message )
   {
      try {
	
         output.writeObject( "SERVER> " + message );
         output.flush();
         displayArea.append( "\nSERVER> " + message );	

      }
		
      catch ( IOException io )
      {
         displayArea.append( "Erro ao escrever a mensagem" );
      }
   }
	
   public static void main( String args[] )
   {
      Server win = new Server();
		
      win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		
      win.runServer();
   }

}

Client.java

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

public class Client extends JFrame {

   private JTextField enterField;
   private JTextArea displayArea;
   private ObjectOutputStream output;
   private ObjectInputStream input;
   private String message = "";
   private String chatServer;
   private Socket client;
	
   public Client( String host )
   {
      super( "Client" );
		
      chatServer = host;
		
      Container box = getContentPane();
		
      enterField = new JTextField();
      enterField.setEnabled( false );
		
      enterField.addActionListener(
		
         new ActionListener() {
			
            public void actionPerformed( ActionEvent e )
            {
               sendData( e.getActionCommand() );
               enterField.setText( "" );	
            }
         }		
      );
		
      box.add( enterField, BorderLayout.NORTH );
		
      displayArea = new JTextArea();
      box.add( new JScrollPane( displayArea ), BorderLayout.CENTER );
		
      setSize( 300, 150 );
      setVisible( true );
   }
	
   public void runClient()
   {
      try {
		
         // Etapa 1: cria um socket para fazer a conexao
         connectToServer();
			
         // Etapa 2: obtem os fluxos de entrada e saida
         getStreams();
			
         // Etapa 3: processa a conexao
         processConnection();
			
         // Etapa 4: fecha a conexao			
         closeConnection();
      }
		
      catch ( EOFException e1 )
      {
         System.out.println( "O Servidor encerrou a conexao" );
      }
		
      catch ( IOException e2 )
      {
         e2.printStackTrace();
      }
   }

   private void getStreams() throws IOException
   {
      output = new ObjectOutputStream( client.getOutputStream() );
      output.flush();
      input = new ObjectInputStream( client.getInputStream() );
		
      displayArea.append( "\nGot I/O streams\n" );
   }

   private void connectToServer() throws IOException
   {
      displayArea.setText( "Fazendo a conexao..." );
		
      client = new Socket( InetAddress.getByName( chatServer ), 6000 );
		
      displayArea.append( "Conectado a: " + client.getInetAddress().getHostName() );
   }

   private void processConnection() throws IOException
   {
      enterField.setEnabled( true );
		
      do {
		
         try {
			
            message = ( String ) input.readObject();
            displayArea.append( "\n" + message );
            displayArea.setCaretPosition( displayArea.getText().length() );
         }
			
         catch ( ClassNotFoundException classNotFound )
         {
            displayArea.append( "\n**Tipo de objeto recebido desconhecido**" );
         }
		
      } while ( !message.equals( "SERVER> exit" ) );
   }

   private void closeConnection() throws IOException
   {
      displayArea.append( "\nFechando conexao" );
      output.close();
      input.close();
      client.close();
   }
	
   private void sendData( String message )
   {
      try {
		
         output.writeObject( "CLIENT> " + message );
         output.flush();
         displayArea.append( "\nCLIENT> " + message );
      }
		
      catch ( IOException io )
      {
         displayArea.append( "Erro ao enviar mensagem" );
      }
   }

   public static void main( String[] args )
   {
      String host = JOptionPane.showInputDialog( null, "Digite o host: " );
		
      Client win = new Client( host );
		
      win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		
   win.runClient();
   }

}
M

e respondendo a tua pergunta da mensagem privada, pra abrir um programa, pode fazer assim:

try {

   Runtime.getRuntime().exec( "C:\\AlgumPrograma.exe" );

} catch( Exception e ) {}
Criado 17 de novembro de 2003
Ultima resposta 22 de nov. de 2003
Respostas 4
Participantes 2