Olá pessoal
Estou implementando um sistema de chat p2p hibrido.
Servidor mantem uma lista de clientes conectados.
Cliente recebe a lista de usuários do servidor e fica abrindo janelas para cada chat.
mantenho a lista dentro de uma jList dentro da classe Contatos que extende jFrame.
A ideia era ter uma Thread que ficaria escutando na porta 6689 as mensagens e com isso encaminhar para a os objetos da classe Chat correspondente ao usuario que enviou a mensagem.
Porem quando dou run() na thread a tela da classe contatos trava e não dá para fazer mais nada.
Se alguem puder ajudar agradeço pretendo deixar o codigo aqui depois para uso e consulta
package clienteredes;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author GERMANO
*/
public class ThreadMensagens extends Thread{
ServerSocket socketRecepcao;
Contatos pai;
public ThreadMensagens(Contatos pai) {
this.pai = pai;
}
@Override
public void run(){
try{
socketRecepcao = new ServerSocket(6689);
}
catch(Exception ex){
System.out.println(ex.getMessage());
//JOptionPane.showMessageDialog(null, "Problema ao abrir porta 6689 de conexão para escutar as mensagens!\n"+ex.getMessage());
}
while( true ) {
System.out.println("Thread loop");
try{
Thread.sleep(100);
Socket socketConexao = socketRecepcao.accept();
BufferedReader bufferLeitura = new BufferedReader(new InputStreamReader(socketConexao.getInputStream()));
DataOutputStream trafegoSaida = new DataOutputStream(socketConexao.getOutputStream());
InetAddress ip = socketConexao.getInetAddress();
String dados= bufferLeitura.readLine();
System.out.println("Thread p1");
String codigo, corpo;
codigo = (String) dados.subSequence(0, 3);
corpo = dados.subSequence(4, (dados.length()-1)).toString();
System.out.println(dados);
switch(Integer.parseInt(codigo)){
case 400 :
this.pai.noticiarMensagem(corpo, ip+"");
trafegoSaida.writeBytes("401\n");
break;
case 600:
break;
}
System.out.println("Thread p3");
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Ih deu pau aqui sabe deus o porque, mas leia a mensagem:\n"+ex.getMessage());
}
yield();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package clienteredes;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author GERMANO
*/
public class Chat extends javax.swing.JFrame {
StringBuffer b = new StringBuffer();
Usuario amigo;
/**
* Creates new form NewJFrame
*/
public Chat(Usuario u) {
initComponents();
area.setContentType("text/html");
this.amigo = u;
this.setTitle(u.getNome()+"@+"+u.getEndereco());
}
public Chat() {
initComponents();
area.setContentType("text/html");
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
area = new javax.swing.JEditorPane();
msg = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(area);
msg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
msgActionPerformed(evt);
}
});
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)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
.addComponent(msg))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(msg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(40, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public Usuario getAmigo(){
return this.amigo;
}
private void msgActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println(area.getText());
try{
Socket socketCliente = new Socket("192.168.2.12", 6689);
DataOutputStream trafegoSaida = new DataOutputStream(socketCliente.getOutputStream());
BufferedReader doServidor = new BufferedReader(new InputStreamReader(socketCliente.getInputStream()));
trafegoSaida.writeBytes("400 "+msg.getText()+ "\n");
socketCliente.setSoTimeout(5000);
String dados = doServidor.readLine();
if(dados.equals("401")){
b.append("<b>Eu:</b>"+msg.getText()+" <br>");
}
else{
b.append("<em style=\"color:#808080\">Eu:"+msg.getText()+"</em> <br>");
b.append("<b style=\"color:#D40000\">*não foi possivel enviar sua mensagem</b>");
}
}
catch(Exception ex){
b.append("<em style=\"color:#808080\">Eu:"+msg.getText()+"</em> <br>");
b.append("<b style=\"color:#D40000\">*não foi possivel enviar sua mensagem</b> <br>");
}
area.setText(b.toString());
msg.setText("");
}
public void novaMensagem(String m){
b.append("<b style=\"color:#007FFF\">"+this.amigo.getNome()+":</b>"+msg.getText()+" <br>");
area.setText(b.toString());
}
/**
* @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
*/
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(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Chat.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 Chat().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JEditorPane area;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField msg;
// End of variables declaration
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package clienteredes;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* @author GERMANO
*/
public class Contatos extends javax.swing.JFrame {
List<Usuario> usuarios =new ArrayList<Usuario>();
List<Chat> telasChat = new ArrayList<Chat>();
ThreadMensagens gerenciadorMensagens;
/**
* Creates new form Contatos
*/
public Contatos(List<Usuario> usuarios) {
this.usuarios = usuarios;
initComponents();
Vector<String> nomes = new Vector<String>();
for(Usuario u: usuarios){
nomes.add(u.getNome());
}
lUsuarios.setListData(nomes);
System.out.println("iniciou 1");
this.setVisible(true);
//inciaGerenciadorMsg();
//this.run();
}
public Contatos(){
initComponents();
}
public void inciaGerenciadorMsg(){
gerenciadorMensagens = new ThreadMensagens(this);
gerenciadorMensagens.run();
System.out.println("iniciou 2");
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
lUsuarios = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lUsuariosMouseClicked(evt);
}
});
jScrollPane1.setViewportView(lUsuarios);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void lUsuariosMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
String nome = lUsuarios.getSelectedValue().toString();
for(Usuario u: usuarios){
if(u.getNome().equals(nome)){
Chat c = new Chat(u);
c.setVisible(true);
}
}
}
public void setLista(){
}
public boolean noticiarMensagem(String msg, String ip){
for(Chat c: telasChat){
if(c.getAmigo().getIP().equals(ip)){
c.novaMensagem(msg);
}
}
return false;
}
/**
* @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
*/
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(Contatos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Contatos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Contatos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Contatos.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 Contatos().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JList lUsuarios;
// End of variables declaration
}