Duvidas com swing , socket e threads

19 respostas
M

Pessoal tinha um server em java , ai com a ajuda do pessoal daqui do forum mesmo consegui torna-lo multi-threads ...porem meu servidor esta muito simples ...
Queria uma parte grafica mais bem elaborada , e tambem queria que cada cliente executado (cada thread criada) abrisse uma janela contendo o que o servidor recebeu do cliente...

package com.servidor;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String args[]) throws Exception {
		int port = 1234;
		
		ServerSocket server = new ServerSocket(port);
		
		Socket request = null;
		ClientThread client = null;
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();
		System.out.println("Servidor inciado no ip! -> "+ip);
		while(true){
			request = server.accept();
			client = new ClientThread(request);
			client.start();
		}

	}
}
package com.servidor;

import java.io.DataInputStream;
import java.net.Socket;

class ClientThread extends Thread {
	private Socket socket;

	public ClientThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {
			DataInputStream in = new DataInputStream(socket.getInputStream());
			String mensagem = in.readUTF();
			String login[] = new String[2];
        	login = mensagem.split("#");
			System.out.println("Servidor-> Recebeu nome : "
					+login[0] );
			
			System.out.println("Servidor-> Recebeu parametro2 : "
					+ login[1] );
			System.out.println("Servidor -> Recebeu parametro3 : "+login[2]);
			System.out.println("Servidor ------> Finalizado ");
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			socket.close();
		} catch (Exception e) {
			System.out
					.println("A problem was observed while closing the connection");
		}
	}
}
Gostaria muito da ajuda de voces....Grato , abraços

19 Respostas

luiz_renato

Vc deve separar a parte de comunicação da parte de exibição (GUI).

De uma maneira simples, na classe servidora, vc tiraria do método main o código e colocaria toda a logica de comunicação num método separado pra que seja invocado por outra classe. A partir de um JFrame que vc criar, vc colocaria p. ex no evento de um botão do JFrame esse código para iniciar o servidor :

Server srv = new Server();
srv.aguardaConexao(); // esse método teria a codificação que está no main atualmente

Na parte cliente, seria parecido já que vc teria JFrame’s pra mostrar o que é recebido do servidor e objetos de comunicação cliente.

É muito bom (caso vc não tenha visto) dar uma olhada no padrão Observable aqui http://www.guj.com.br/articles/47 para que as classes servidora/cliente notifiquem as tela das mudanças ocorridas p. exemplo o que vc faz nesse trecho

System.out.println("Servidor-> Recebeu nome : "  +login[0] );

Vc usaria o padrão pra "avisar" a tua tela que foi recebido o nome…

M

Intendi , muito obrigado pela resposta , vou tentar por em pratica tudo o que voce me falou …
Obrigado , abraços!
Não intendi muito bem a parte da classe observer =//…

M

Essa classe processo que ele cita no exemplo seria minha thread ?

luiz_renato

A classe processo seria tudo aquilo que vc quer que seja observado (que no artigo está implementado numa thread), emfim os processos que estão acontecendo e que vc precisa que seja informado para outras classes; no seu caso processo seriam as partes de server/client que se comunicam e precisam notificar as telas a medida que vão senso executados .

No caso do artigo a nomenclatura processo não é obrigatório e nem faz parte do padrão em si, porém facilita o entendimento.

A classe Observer é aquela que precisa saber o que está acontecendo, isto é quando vc inicia o objeto server a sua tela é um observer pq ela precsa saber quando o servidor está iniciando, recebendo conexões , etc

M

Então a classe "observer" seria minha classe Server e a classe "processo" seria o meu ClientThread ? E a classe GUI ,como ficaria ?
O negócio complicado! ....kkk obrigado pela atenção , abraços

Tentei implementar , olha como ta ficando :

Classe Server , que fiz o que voce falou , coloquei dentro de um metodo.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pservidor;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JTextArea;

public class Server {
//
//	public static void main(String args[]) throws Exception {
	 public String startar () throws IOException{	
            int port = 1234;
		ServerSocket server = new ServerSocket(port);
		Socket request = null;
		Thread client = null;
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();
		System.out.println("Servidor inciado no ip! -> "+ip);
		while(true){
			request = server.accept();
			client = new Thread(new ClientThread(this)); 
			client.start();
                   return ip;    
		}
               
         }
         
         public void desligar (String s2) throws IOException{
	     int port = 1234;
		ServerSocket server = new ServerSocket(port);
		Socket request = null;
		ClientThread client = null;
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();
		System.out.println("Servidor desligado no ip! -> "+ip);
		while(true){
			request = server.accept();
			client = new ClientThread(request);
			client.stop();
		}
         }
}
Esta dando erro nessa parte da Classe Servidor:
client = new Thread(new ClientThread(this));
Classe ClientThread :
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pservidor;

import java.io.DataInputStream;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;

class ClientThread extends Observable implements Runnable{
	private Socket socket;

	public ClientThread(Socket socket) {
		this.socket = socket;
	}

        public ClientThread(Observer observador){
        addObserver(observador);
        }
         public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                
                new Principal().setVisible(true);
            }
        });
    }
	public void run() {
		try {
			DataInputStream in = new DataInputStream(socket.getInputStream());
			String mensagem = in.readUTF();
			String login[] = new String[2];
        	login = mensagem.split("#");
			System.out.println("Servidor-> Recebeu Nome : "
					+login[0] );
			
			System.out.println("Servidor-> Recebeu Mesa : "
					+ login[1] );
			System.out.println("Servidor -> Recebeu Pedido : "+login[2]);
			System.out.println("Servidor ------> Pedido Finalizado ");
                        notifyObservers(new String (login[0]));
                        notifyObservers(new String (login[1]));
                        notifyObservers(new String (login[2]));
                        setChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
                    
			socket.close();
                        notifyObservers(new Boolean(true));
                        setChanged();
		} catch (Exception e) {
			System.out
					.println("A problem was observed while closing the connection");
		}
	}
}
Classe GUI:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pservidor;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.io.IOException;
import pservidor.Server;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author lucas
 */
public class Principal extends javax.swing.JFrame {
    private String[] args;
    /**
     * Creates new form Principal
     */
    public Principal() {
        initComponents();
          }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jDesktopPane1 = new javax.swing.JDesktopPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Servidor");

        jButton1.setText("Listar Conectados");

        jButton2.setText("Conectar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton3.setText("Desconectar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Limpar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Verdana", 0, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(204, 204, 204));
        jLabel1.setText("Painel Servidor");
        jLabel1.setBounds(120, 10, 160, 23);
        jDesktopPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pservidor/servidor.png"))); // NOI18N
        jLabel2.setText("jLabel2");
        jLabel2.setBounds(-10, 0, 430, 50);
        jDesktopPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(164, Short.MAX_VALUE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(129, 129, 129))
            .addComponent(jDesktopPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)
                    .addComponent(jButton3))
                .addGap(31, 31, 31)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addComponent(jButton4)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            Server s1 = new Server();
            s1.startar();
        } catch (IOException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
//      try {
//            Server s1 = new Server();
//                    s1.desligar(null);
//                    
//        } catch (IOException ex) {
//            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
//        }
// 
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
limpar();       
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
  
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Principal().setVisible(true);
            }
        });
    }
    public void limpar (){
        
        jTextArea1.setText("");
     

}
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration                   
}
luiz_renato

O correto seria:

client = new Thread(new ClientThread(request));
M

O restante esta correto ?
OBS : O método UPDATE ficaria em qual classe ? Na GUI ou na server ?

luiz_renato

O update deve ficar nos observer. Quem vai ser o observador? A sua classe GUI.

No Server vc pde criar um atributo Observer que vc passa pro ClientThread na hora da conexão, faz isso via contrutor do Server .
private Observer observer;

public Server(Observer observer) {
		this.observer = observer;
}
Altere o construtor do ClientThread para receber e registrar o Observer:
public ClientThread(Socket socket,Observer observer) {  
	this.socket = socket;  
	addObserver(observer);
}
Na criação do cliente vc passa o Observer junto com o Socket que vc chamou de request:
client = new Thread(new ClientThread(request,this.observer));
Nesse trecho vc tem que colocar setChanged logo depois de notificar e não somente na última notificação:
notifyObservers(new String (login[0]));  
		setChanged();
                notifyObservers(new String (login[1]));  
		setChanged();
                notifyObservers(new String (login[2]));  
		setChanged();

Agora vc tem que pensar que como está criando a conexao do server ao clicar no botão ele fica "preso" até que sejá feita a 1ª conexão de um cliente, então vai "matutando" ...

M

Ta dando erro na hora de estanciar a classe server no botao “iniciar servidor” ,Fala que a classe server precisa de um construtor…mas ja coloquei ,assim como voce falou,
Deixa eu ver se entendi , o problema agora , é que o servidor fica travado até receber a primeira conexão ? Se for isso não tem problema , mas no caso , eu quero que ao inves do SystemOutPrint como tava fazendo , eu quero que ele jogue em um label…como faria isso ?

luiz_renato

Mostre exatamente onde e qual o erro pra dar uma olhada.

M

Server s1 = new Server(); try { s1.startar(); } catch (IOException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); }

Ai eu clico na lampadinha e fala “criar construtor Server()”…

luiz_renato

Tá, se vc implementou o constutor que eu mostrei no Server , esse que vc está usando pra instanciar server assim

Server server = new Server();

chama-se construtor padrão e quando vc não implementou nenhum, vc pode usá-lo sem ter que criá-lo explicitamente assim

public Server () { ...

No teu caso vc tem que usar o construtor que recebe o Observer como te falei lá atrás

public Server(Observer observer) { this.observer = observer; }

Vc tem que chamar o server do evento do botão assim:

Server s1 = new Server(this); //isso indica que a classe que está criando server (Princiipal) é um Observer try { s1.startar(); } catch (IOException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); }
É obvio que antes vc tem que fazer a sua classe GUI Principal implementar a interface Observer com o método update, este inserindo linhas no JTextArea.

M

Ainda ta travando , veja se estou fazendo certo :

Classe GUI :
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pservidor;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.io.IOException;
import pservidor.Server;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author lucas
 */
public class Principal extends javax.swing.JFrame implements Observer  {
    private String[] args;
    /**
     * Creates new form Principal
     */
    public Principal() {
        initComponents();
          }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jDesktopPane1 = new javax.swing.JDesktopPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        jLabel3.setText("jLabel3");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Servidor");

        jButton1.setText("Listar Conectados");

        jButton2.setText("Conectar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Desconectar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Limpar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Verdana", 0, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(204, 204, 204));
        jLabel1.setText("Painel Servidor");
        jLabel1.setBounds(120, 10, 160, 23);
        jDesktopPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pservidor/servidor.png"))); // NOI18N
        jLabel2.setText("jLabel2");
        jLabel2.setBounds(-10, 0, 430, 50);
        jDesktopPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel4.setText("Nome :");

        jLabel5.setText("Mesa :");

        jLabel6.setText("Pedido :");

        jLabel7.setText("jLabel7");

        jLabel8.setText("jLabel8");

        jLabel9.setText("jLabel9");

        jLabel10.setText("jLabel10");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jDesktopPane1)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel7))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel8))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel9)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(164, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel10)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(129, 129, 129))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)
                    .addComponent(jButton3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel9))
                .addGap(57, 57, 57)
                .addComponent(jLabel10)
                .addGap(52, 52, 52)
                .addComponent(jButton4)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     Server s1 = new Server(this); //isso indica que a classe que está criando server (Princiipal) é um Observer  
        try {
            s1.startar();
        } catch (IOException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
             
       
            
       
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
//      try {
//            Server s1 = new Server();
//                    s1.desligar(null);
//                    
//        } catch (IOException ex) {
//            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
//        }
// 
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
limpar();       
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
  
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Principal().setVisible(true);
            }
        });
    }
    public void limpar (){
        
        
     

}
    public void update(Observable o, Object arg) {
		if(arg instanceof String) {
			//Seta o valor do progresso
			jLabel7.setText(  String.valueOf(((Integer) arg).intValue()));
		} else if(arg instanceof Boolean) {
			if( ((Boolean) arg).booleanValue() ) {
				jLabel10.setText("Servidor finalizado!");
			}
		}
	}
    
    
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    // End of variables declaration
}

Classe server :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pservidor;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observer;
import javax.swing.JTextArea;

public class Server {
    private Observer observer;
   
   public Server(Observer observer)
   {
       this.observer = observer;
   }
//
//	public static void main(String args[]) throws Exception {
	 public void startar () throws IOException{	
            int port = 1234;
		ServerSocket server = new ServerSocket(port);
		Socket request = null;
		Thread client = null;
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();
		System.out.println("Servidor inciado no ip! -> "+ip);
		while(true){
			request = server.accept();
			client = new Thread(new ClientThread(request,this.observer)); 
			client.start();
   
		}
               
         }
         
         public void desligar (String s2) throws IOException{
	     int port = 1234;
		ServerSocket server = new ServerSocket(port);
		Socket request = null;
		Thread client = null;
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();
		System.out.println("Servidor desligado no ip! -> "+ip);
		while(true){
			request = server.accept();
			client = new Thread(new ClientThread(request,this.observer)); 
			client.stop();
		}
         }
         
         
         
         
}

Classe Thread :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pservidor;

import java.io.DataInputStream;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;

class ClientThread extends Observable implements Runnable{
	private Socket socket;

	public ClientThread(Socket socket,Observer observer) {
		this.socket = socket;
                addObserver(observer);
	}

      
         public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                
                new Principal().setVisible(true);
            }
        });
    }
	public void run() {
		try {
			DataInputStream in = new DataInputStream(socket.getInputStream());
			String mensagem = in.readUTF();
			String login[] = new String[2];
        	login = mensagem.split("#");
			System.out.println("Servidor-> Recebeu Nome : "
					+login[0] );
			
			System.out.println("Servidor-> Recebeu Mesa : "
					+ login[1] );
			System.out.println("Servidor -> Recebeu Pedido : "+login[2]);
			System.out.println("Servidor ------> Pedido Finalizado ");
                        notifyObservers(new String (login[0]));
                        setChanged();
                        notifyObservers(new String (login[1]));
                        setChanged();
                        notifyObservers(new String (login[2]));
                        setChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
                    
			socket.close();
                        notifyObservers(new Boolean(true));
                        setChanged();
		} catch (Exception e) {
			System.out
					.println("A problem was observed while closing the connection");
		}
	}
}
luiz_renato

Faz o Server virar uma Thread e colocando em run o método startar e executa como Thread em Principal.

E troca em update por

jLabel7.setText( arg.toString());

M
Coloquei isso no Jbutton Click :
Thread server = null;
    server = new Thread(new ClientThread(request,this.observer));
Só que esta dando erro : "Cannot find symbol - symbol : variavel request"...

OLha como esta meu server transformado em Thread :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pservidor;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

public class Server extends Thread{
    private Observer observer;
   
   public Server(Observer observer)
   {
       this.observer = observer;
   }
//
//	public static void main(String args[]) throws Exception {
   
   public void run(){
        try {
            this.startar();
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
   }
	 public void startar () throws IOException{	
            int port = 1234;
		ServerSocket server = new ServerSocket(port);
		Socket request = null;
		Thread client = null;
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();
		System.out.println("Servidor inciado no ip! -> "+ip);
		while(true){
			request = server.accept();
			client = new Thread(new ClientThread(request,this.observer)); 
			client.start();
   
		}
               
         }
         
         public void desligar (String s2) throws IOException{
	     int port = 1234;
		ServerSocket server = new ServerSocket(port);
		Socket request = null;
		Thread client = null;
		InetAddress addr = InetAddress.getLocalHost();
		String ip = addr.getHostAddress().toString();
		System.out.println("Servidor desligado no ip! -> "+ip);
		while(true){
			request = server.accept();
			client = new Thread(new ClientThread(request,this.observer)); 
			client.stop();
		}
         }
         
         
         
         
}

Muito obrigado pela força cara , esta sendo de grande ajuda !

luiz_renato

No evento do botão basta vc colocar:

Server s1 = new Server(this); new Thread(s1).start();

M

Ele só esta pegando a ultima coisa que o cliente mandou , no caso o parametro 3 , e gostaria de saber ,como fazer pra a cada client conectado ele abrir um novo frame contendo o nome , e os parametros ?
Obrigado pela ajuda , abraços !

M

Consegui resolver o restante , agora so tem o problema dele pegar a ultima coisa que o client manda, =X…Tem como eu pegar um por um ?

M

Ninguem galera ? Falta pouca coisa !

Criado 13 de julho de 2012
Ultima resposta 16 de jul. de 2012
Respostas 19
Participantes 2