Estou a desenvolver um programa para a comunicação entre cliente e servidor.
Estou a desenvolver a interface gráfica do programa com base em JPanel
/Forms
.
Os dados do cliente são enviados corretamente para o servidor. O meu problema é quando faço para ir buscar os dados do servidor de novo para o cliente, a interface gráfica bloqueia, e não são mostrados elementos que deveriam aparecer.
Cliente
package Interfaces;
import Classes.Mensagem;
import Classes.Utilizador;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Zé Luís
*/
public class ConversaGrupo extends javax.swing.JFrame {
private static Utilizador userClass;
private String serverID;
private Socket socket = null;
private int port = 2048;
private String host;
private Utilizador utilizador;
private Mensagem mensagemServidor;
private static PrintWriter out = null;
private static BufferedReader in = null;
private static String mensagemServidorThr;
/**
* Creates new form ConversaGrupo
*/
public ConversaGrupo(Utilizador cd, String serverID) {
this.userClass = cd;
this.serverID = serverID;
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() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jButton2 = new javax.swing.JButton();
text_toClienteEscrever = new javax.swing.JTextField();
enviar_Button = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
areaChat = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setBackground(new java.awt.Color(230, 230, 230));
jButton1.setText("CRIAR GRUPO");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jList1.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(jList1);
jButton2.setText("MENSAGEM PRIVADA");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane2)))
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jButton2)
.addContainerGap(16, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 301,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
enviar_Button.setText("ENVIAR");
enviar_Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
enviar_ButtonActionPerformed(evt);
}
});
jButton4.setText("SAIR");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
areaChat.setColumns(20);
areaChat.setRows(5);
areaChat.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
areaChatMouseClicked(evt);
}
});
jScrollPane3.setViewportView(areaChat);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(text_toClienteEscrever,
javax.swing.GroupLayout.PREFERRED_SIZE, 414, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(enviar_Button, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jScrollPane3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 333,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(text_toClienteEscrever, javax.swing.GroupLayout.PREFERRED_SIZE,
40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(enviar_Button)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)))
.addContainerGap(25, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void areaChatMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
areaChat.setText("BEM-VINDO \t" + userClass.getNome());
connectServer();
try {
receberDadosServidor();
} catch (IOException ex) {
Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void enviar_ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//verifica se a caixa de texto está vazia
if (text_toClienteEscrever.getText() != null) {
//envia para o servidor a mensagem que o user escreveu
out.println(userClass.getNome() + ":" + text_toClienteEscrever.getText());
out.flush();
text_toClienteEscrever.setText("");
}
}
private void connectServer() {
try {
socket = new Socket(host, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
areaChat.setText(areaChat.getText() + "\nLigação com o servidor estabelecida!\n");
text_toClienteEscrever.requestFocus();
} catch (IOException ex) {
areaChat.setText(areaChat.getText() + "\n Erro com o servidor\n");
}
}
private void receberDadosServidor() throws IOException {
String fromServer = null;
while ((fromServer = in.readLine())!= null) {
System.out.println("Servidor: " + fromServer);
areaChat.setText(areaChat.getText() + "\n" + fromServer);
}
}
// Variables declaration - do not modify
private javax.swing.JTextArea areaChat;
private javax.swing.JButton enviar_Button;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton4;
private javax.swing.JList<String> jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextField text_toClienteEscrever;
// End of variables declaration
}
A janela com os elementos abrem, mas os problemas começam quando o programa entra directamente no método formWindowsOpened()
.
Quando entra no método e com o debugger passa pelas linhas, mas bloqueia e não aparece a mensagem "BEM VINDO" como podem verificar pela linha areaChat.setText("BEM-VINDO \t" + userClass.getNome());
.
A interface bloqueia, e só parando a execução do servidor e cliente é que consigo que as janelas fechem.
Sei que está relacionado com o método receberDadosServidor()
mas não entendo o porque, da Interface, bloquear.
private void receberDadosServidor() throws IOException {
String fromServer = null;
while ((fromServer = in.readLine())!= null) {
System.out.println("Servidor: " + fromServer);
areaChat.setText(areaChat.getText() + "\n" + fromServer);
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
areaChat.setText("BEM-VINDO \t" + userClass.getNome());
connectServer();
try {
receberDadosServidor();
} catch (IOException ex) {
Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
}
}
Lado do Servidor
import Classes.Utilizador;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Classe responsável por albergar o servidor do programa.
*
* @author Zé Luís
*/
public class server {
/**
* O servidor corre quando antige o método main.
*
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
ServerSocket srvSckt = null;
int porto = 2048;
boolean listening = true;
//conecao ao servidor
try {
srvSckt = new ServerSocket(porto);
System.out.println("Conecção ao Servidor efectuada com sucesso!");
} catch (IOException ex) {
System.err.println("Impossível coneção a porta \t" + porto);
}
Socket clientSocket = null;
clientSocket = srvSckt.accept(); //espera por pedidos de clientes.
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String fromServerIntoServer = null;
// out.println(in.readLine());
while (listening) {
out.println(in.readLine());
}
srvSckt.close();
clientSocket.close();
out.close();
in.close();
}
}
Em baixo deixo o exemplo da Interface Gráfica, onde na TextArea
não aparece nada. Fica tudo bloqueado e só consigo fechar a janela se parar a execução do programa.
Solução Adicionei uma Thread a classe do cliente para nao haver concorrencia entre a interface e o socket.
Thread recever = new Thread() {
public void run() {
try {
receberDadosServidor();
} catch (IOException ex) {
Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
recever.start();
Classe completa
private void formWindowOpened(java.awt.event.WindowEvent evt) {
areaChat.setText("BEM-VINDO \t" + userClass.getNome());
connectServer();
//devido a concorrencia de recursos, necessitamos de uma thread.
Thread recever = new Thread() {
public void run() {
try {
receberDadosServidor();
} catch (IOException ex) {
Logger.getLogger(ConversaGrupo.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
recever.start();
}