Sugestões de Aplicações no Chat

4 respostas
_

Preciso de idéias e códigos do que implementar nesse chat

pensei em fazer envio de arquivos ou fazer uma interface melhor, já que a janela é um text area e um textfield com o fundo preto com letras verdes

Ajudem-me com códigos e idéias
Derivei de outro chat alguma coisas e estou implementando o que consigo
É trabalho final e preciso fazer algo bom!!

ps: Sou bem iniciante, quem puder dar uma mão eu serei eternamente grato

Servidor

/*
 *
*/
 
import java.net.*;
import java.io.*;
import java.util.*;

public class Servidor {
  public Servidor (int port) throws IOException {
    ServerSocket sSocket = new ServerSocket (port); //cria uma nova socket na porta port
    //loop infinito que fica a espera de clientes criando uma nova ligacao sempre que um usuário se conecta
    while (true) {
      Socket cSocket = sSocket.accept ();// espera por conexao
      System.out.println (">> Usuario conectado: " + cSocket.getInetAddress ());
      
      Chat c = new Chat (cSocket);// cria conexao
      c.start ();// inicia a thread
    }
  }

  public static void main (String args[]) throws IOException {
    if (args.length != 1)
      throw new RuntimeException ("»Erro: Servidor <port> \n(\"Falta numero da porta ou formato incorreto\")");
    new Servidor (Integer.parseInt (args[0]));
  }
}

Cliente

/**
 *
 */
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.SystemColor.*;
import javax.swing.*;
import java.awt.Component.*;

public class Cliente extends Frame implements Runnable {
  protected DataInputStream input;//i
  protected DataOutputStream output;//o

  protected TextArea taSaida;//saida
  protected TextField tfEntrada;//msgentrada;

  protected Thread listener;
  
  public Cliente (String title, InputStream input, OutputStream output) {
    super (title);
    this.input = new DataInputStream (new BufferedInputStream (input));
    this.output = new DataOutputStream (new BufferedOutputStream (output));
    setLayout (new BorderLayout ());
    add ("North", taSaida = new TextArea ());
    taSaida.setEditable (false);
    taSaida.setBackground(Color.BLACK);
    taSaida.setForeground(Color.GREEN);
    
    Font f=new Font("Verdana",Font.BOLD,12);
    taSaida.setFont(f);
    add ("South", tfEntrada = new TextField ());
    tfEntrada.setForeground(Color.BLUE);
    taSaida.setFont(f);
    pack ();
    show ();
 
    listener = new Thread (this);
    listener.start ();
    tfEntrada.requestFocus ();
  }

  public void run () {
    if (tfEntrada.equals("")){
    } else{
        try {
            while (true) {
                String line = input.readUTF ();
                taSaida.appendText (line + "\n");
            }
        } catch (IOException ex) {
            ex.printStackTrace ();
        } finally {
            listener = null;
            tfEntrada.hide ();
            validate ();
            try {
                output.close ();
            } catch (IOException ex) {
                ex.printStackTrace ();
            }
        }
    }
  }

  public boolean handleEvent (Event e) {
    
        if ((e.target == tfEntrada) && (e.id == Event.ACTION_EVENT)) {
            try {
                output.writeUTF ((String) e.arg);
                output.flush ();
            } catch (IOException ex) {
                ex.printStackTrace();
                listener.stop ();
            }
            tfEntrada.setText ("");
            return true;
        } else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
            if (listener != null)
                listener.stop ();
            hide ();
            return true;
        }
        return super.handleEvent (e);
    }

  public static void main (String args[]) throws IOException {
      if (args.length != 2)
          throw new RuntimeException ("»Erro: Cliente <host> <port> \n(\"Servidor nao encontrado, numero ip e/ou numero da porta\")");
      Socket s = new Socket (args[0], Integer.parseInt (args[1]));
      new Cliente ("..::MaTrIX ChAt::..(para ajuda digite /help) [" + args[0] + "]:[" + args[1] + "]",s.getInputStream (), s.getOutputStream ());
  }
}

Informações Cliente

/**
 * @author Alisson, Marlon, Thales
 *
 */
 
import java.net.*;
import java.io.*;
import java.util.*;

class conexao
{
    public String pessoa;
    public Chat c;//faz referencia ao objeto do cliente nome 
    conexao(String pessoa,Chat c)
    {
        this.pessoa=pessoa;
        this.c=c;
    }
}

public class Chat extends Thread {
  protected Socket s;
  protected DataInputStream i;
  protected DataOutputStream o;
  
  public Chat (Socket s) throws IOException {
    this.s = s;
    i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
    o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
  }
  //Cria vetores
  protected static Vector handlers = new Vector ();
  protected static Vector infoclient = new Vector ();//
  
  //adiciona o nome do cliente ao vetor infoclient
  public void adiciona_cliente(String pessoa,Chat c)
  {
      synchronized (infoclient) {
          infoclient.addElement(new conexao(pessoa,c));
      }
  }
  
  //envia mensagem privada 
  public void msg_privada(String usuario,String texto,Chat c,String quem)
  {
      conexao v; 
      try {
          c.o.writeUTF ("Mensagem privada de: "+quem+" -"+texto);//envia a mensagem privada
          c.o.flush ();
      } catch (IOException ex) {
     
          c.stop ();
      }
  }
  
  
  public void run () {
    String pessoa=null;
    conexao v;
    int a;
    Chat r=null;
    Enumeration e;
    String array[]=null;

    int existe;
    try {
      String msg = null;
      pessoa="Visitante";//inicializa o nome como visitante 
      handlers.addElement (this);
      
      while (true) {
          msg = i.readUTF ();
          array=msg.split(" ");//divide o texto pelos espaços
          //  compara a primeira palavra com "/nick"
          if(msg.length()>5 && array[0].compareTo("/nick")==0)
          {
              if(array.length > 2)//se tiver espaços
              {
                  try {
                      this.o.writeUTF ("»Não escreva espaços no nome!!!!!");
                      this.o.flush ();
                  } catch (IOException ex) {
                      this.stop ();
                  }
              }
              else
              {
                  a=0;
                
                  synchronized (infoclient) {
                      e=infoclient.elements(); 
                    
                      while (e.hasMoreElements ()) {
                          v=(conexao)e.nextElement();
                          if(v.pessoa.compareTo(msg.substring(6))==0)
                              a=1; 
                      }
                      //se o nome ainda não existe adiciona o nome ao vector infoclient
                      if(a!=1)
                      {
                            adiciona_cliente( msg.substring(6),this );
                            pessoa=msg.substring(6);
                            broadcast ("»" + pessoa + " entrou...");
                      }
                else
                {
                    try {
                       
                            this.o.writeUTF ("»Nick existente!");
                            this.o.flush ();
                    } catch (IOException ex) {
                        this.stop ();
                    }   
                }
            }
        }
        }
        else
            //compara a primeira palavra com "/mp"    
            if(msg.length()>3 && array[0].compareTo("/mp")==0)
            {
                
                if(array.length < 2)//testa se foi introduzido o nome do usuário destino
                {
                    try {
                       this.o.writeUTF ("»Escreva o nome do destinatario!\n»Exemplo: /mp \"destinatario\" \"mensagem\"");
                       this.o.flush ();//limpa a fila
                    } catch (IOException ex) {
                        this.stop ();//para a thread
                    }
                }
                else
                {
                //não deixa o usuário Visitante enviar mensagens privadas
                if(pessoa.compareTo("Visitante")!=0)
                {
                    array=msg.split(" ");//divide o texto
                    String usuario=array[1];
                    String texto=msg.substring(msg.indexOf(usuario)+array[1].length());
                    synchronized (infoclient) {
                        e=infoclient.elements();
                        existe=0;
                        while (e.hasMoreElements ()) {
                            v=(conexao)e.nextElement();
                            System.out.println(pessoa);
                            //verifica se o usuário destino existe
                            //se existe envia a mensagem
                            if(v.pessoa.compareTo(usuario)==0)
                            {
                                existe=1;
                                r=v.c;//endereço
                                msg_privada(usuario,texto,r,pessoa);
                            }
                        }
                        
                    }
                    // se o usuário destino não existir da a informação
                    if (existe==0)
                    {
                        try {
                            this.o.writeUTF ("»O usuário "+usuario+" não existe!");
                            this.o.flush ();
                        } catch (IOException ex) {
                            this.stop ();
                        }    
                    }       
                }
                }
            }
            else
                if(msg.length()==5 && array[0].compareTo("/list")==0)
                {
                    synchronized (infoclient) {
                      e=infoclient.elements(); 
                      this.o.writeUTF ("\nUsuarios do ..::MaTrIX ChAt::..:");
                      while (e.hasMoreElements ()) {
                          v=(conexao)e.nextElement();
                          this.o.writeUTF (v.pessoa);
                           this.o.flush ();
                      }
                      this.o.writeUTF("\n");
                    }
                }
                else
                {
                //verifica se a palavra escrita é /quit para sair
                if (msg.length()==5 && array[0].compareTo("/quit")==0)
                {
                    handlers.removeElement (this);
                    broadcast ("»" + pessoa + " Saiu...");
                    
                    synchronized (infoclient) {
                        e=infoclient.elements(); 
                    //loop para ver se existe o nome de usuário introduzido
                    while (e.hasMoreElements ()) {
                        v=(conexao)e.nextElement();
               
                        if(v.pessoa.compareTo(pessoa)==0){
                          
                            this.o.writeUTF (">>O cliente foi eliminado!!<<");
                            this.o.flush ();
                           
                            //elimina o cliente do vector se ele já etiver saido
                            infoclient.remove(infoclient.elementAt(infoclient.indexOf(v)));
                          
                        }
                    }
                    s.close();
                    this.stop();
                    
                    }
                    
                }
                //verifica se a palavra escrita é /help e informa os comandos
                else if (msg.length()==5 && array[0].compareTo("/help")==0)
                {
                	this.o.writeUTF ("» Comandos \n /nick digite /nick e seu nome\n /list para listar usuários do chat \n /mp \"nome\" \"mensagem\" para enviar mensagem privada \n /quit para sair ");
                	this.o.flush ();
                }
                
                //envia mensagem se o nome for diferente de "Visitante"
                if(pessoa.compareTo("Visitante")!=0)
                    broadcast (pessoa + " - " + msg);
                else
                {
                    try {
                            this.o.writeUTF ("»O seu nome ainda não foi registrado!\nEscreva: /nick \"nome\"");

                            this.o.flush ();
                    } catch (IOException ex) {
                        this.stop ();
                    }
                }
            }
      }
     
    } catch (IOException ex) {
        ex.printStackTrace ();
    } finally {
       
         try {
            s.close ();
         } catch (IOException ex) {
             ex.printStackTrace();
         }
    }
  }
 //envia mensagem para todos
  protected static void broadcast (String message) {
    synchronized (handlers) {
        Enumeration e = handlers.elements ();
        while (e.hasMoreElements ()) {
            Chat c = (Chat) e.nextElement ();
            try {
                synchronized (c.o) {
                    c.o.writeUTF (message);
                }
                c.o.flush ();
            } catch (IOException ex) {
                 c.stop ();
            }
        }
    }
  }

}

4 Respostas

_

esqueci de falar que vcs já podem postar

:lol: :lol: :lol:

C

DUvidas ? :roll:

_

OpA!

várias duvidas, na verdade queria sugestões do que eu poderia aplicar nesse chat
tentei várias coisas e não da nada certo

pensei em aplicar envio de arquivo
colocar emocions
ou fazer um textarea que mostrasse os onlines igual ao mirc

como vês tenho idéias, mas não sei aplicar, por isso pedi sugestões, até para não impor minha sugestões, vai que alguém tenha uma idéia diferente já implementado, mas to no aguardo que alguém posso me ajudar :wink:

C

A chave disso está em tu criar o seu próprio protocolo, ou seja… mensagens que tu envia com um determinado codigo, q o seu cliente ou server… entende e mostra o emotion…
quanto ao envio de arquivos…
basicamente… eu vai ter q ler o seu arquivo e transforma-lo em um array de bytes, depois enviar no write do seu output, ok ?

Criado 26 de junho de 2007
Ultima resposta 29 de jun. de 2007
Respostas 4
Participantes 2