Implementar um server multithreaded e vários clientes

0 respostas
L

Eu sou muito noob em java...
eu peguei um programa java exemplo e construi meu client / server...
um se comunica com o outro tranquilamente...
Pesquisei nesse forum como fazer um sistema multiclient e vi que daria pra fazer multi-threaded.
Mas eu não entendi como fazer isso, e eu não sei mto de java... por isso queria pedir ajuda de vocês...
E eu nem sei se a melhor maneira mesmo é multi-threaded ou nao...
estava pensando do meu server abrir várias conexoes... mas eu nao sei como passar de um para outro...

Gostaria muito da ajuda de vocês...

o meu server:

package server;

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 java.net.Socket connection;
    private int counter = 1;
    public int i=8000;
    public Server(){

   super("Server");

   Container container = getContentPane();

   enterField = new JTextField();
   enterField.setEnabled(false);

   enterField.addActionListener(

       new ActionListener(){

      public void actionPerformed(ActionEvent event){

          sendData(event.getActionCommand());

      }
      
       }

       );

   container.add(enterField, BorderLayout.NORTH);

   displayArea = new JTextArea();
   container.add(new JScrollPane(displayArea),BorderLayout.CENTER);

   setSize(300,150);
   setVisible(true);

    }

    public void runServer(){

   try{

  
	   server = new ServerSocket(8000);
	   
       while(true){

      waitForConnection();
      getStreams();
      processConnection();
      closeConnection();
      ++counter;

       
      }
   }

   catch(EOFException eofException){
       System.out.println("O Cliente Encerrou a Conexão.");
   }

   catch(IOException ioException){

       ioException.printStackTrace();

   }

    }

    private void waitForConnection() throws IOException{
    
    displayArea.setText("Esperando pela conexão...\n");
   connection = server.accept();
  
   displayArea.append("Conexão " + counter + " recebida por: " + connection.getInetAddress().getHostName());
   
   }

    private void getStreams() throws IOException{

   output = new ObjectOutputStream(connection.getOutputStream());
   output.flush();
   input = new ObjectInputStream(connection.getInputStream());
   displayArea.append("fluxos de entrada e saída recebidos...");

    }

    private void processConnection() throws IOException{

   String message = "SERVER: CONEXÃO EFETUADA COM SUCESSO!";
   output.writeObject(message);
   output.flush();

   enterField.setEnabled(true);
   do{

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

       catch(ClassNotFoundException classNotFoundException){

      displayArea.append("Objeto digitado desconhecido...");

       }
   } while(!message.equals("CLIENT: TERMINATE"));

    }

    private void closeConnection() throws IOException{

   displayArea.append("O Usuário terminou a sessão.");
   enterField.setEnabled(false);
   output.close();
   input.close();
   connection.close();

    }

    private void sendData(String message){

   try{

       output.writeObject("\nSERVER: " + message);
       output.flush();
       displayArea.append("\nSERVER: " + message);

   }

   catch(IOException ioException){

       displayArea.append("Erro ao escrever o objeto");

   }

    }

    public static void main(String args[]){

   
   Server application = new Server();
   application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   application.runServer();
   

    }

}

O meu cliente:

package client;
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 java.net.Socket client;
    
    public Client(String host){

   super("Client");

   chatServer = host;
   Container container = getContentPane();
   enterField = new JTextField();
   enterField.setEnabled(true);
   JButton bot = new JButton("OK");
   
    enterField.addActionListener(

                 new ActionListener(){

                public void actionPerformed(ActionEvent event){

                    sendData(event.getActionCommand());

                }
               
                 }
               
        );

   container.add(enterField,BorderLayout.NORTH);
   container.add(bot, BorderLayout.SOUTH);
   displayArea = new JTextArea();
   
   container.add(new JScrollPane(displayArea),BorderLayout.CENTER);
   setSize(300,150);
   setVisible(true);
displayArea.setText("teste\n"+host);

bot.addActionListener(new ActionListener(){

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
		displayArea.setText("Mandando Texto\n");
		sendData(enterField.getText());
	}
 });


runClient();
    }

    public void runClient(){

   try{
displayArea.setText("\nteste");
       connectToServer();
       getStreams();
       processConnection();
       closeConnection();

   }

   catch(EOFException eofException){

       System.out.println("O Servidor encerrou a conexão");

   }

   catch(IOException ioException){

       ioException.printStackTrace();

   }

    }

    private void getStreams() throws IOException{

   output = new ObjectOutputStream(client.getOutputStream());
   output.flush();

   input = new ObjectInputStream(client.getInputStream());

   displayArea.append("\nFluxo de entrada e saída carregados");

    }

    private void connectToServer() throws IOException{

   displayArea.setText("Esperando a conexão");

   client = new java.net.Socket("127.0.0.1",8000);

   displayArea.append("Conectado com: " + 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 classNotFoundException){
      
      displayArea.append("Ojeto digitado desconhecido");
      
       }

   }
   while(!message.equals("SERVER: TERMINATE"));
    }

    private void closeConnection() throws IOException{

   displayArea.append("\nFechando a conexão...");
   output.close();
   input.close();
   client.close();

    }

    private void sendData(String message){

   try{

	  // output.writeObject("CLIENT: " + to);
	   output.writeObject("CLIENT: " + message);
       output.flush();
       displayArea.append("\nCLIENT: "+ message);

   }

   catch(IOException ioException){

       displayArea.append("\nErro ao escrever o objeto");

   }

    }

    public static void main(String args[]){

   Client application;

   if(args.length == 0){

       application = new Client("localhost");

   }
   else{

       application = new Client(args[0]);

       application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       application.runClient();

   }

    }

}

vlw...

Criado 27 de novembro de 2008
Respostas 0
Participantes 1