Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Java - Aiuto per Chat in Java
Forum - Java - Aiuto per Chat in Java

Avatar
Java5 (Ex-Member)
Rookie


Messaggi: 23
Iscritto: 19/10/2009

Segnala al moderatore
Postato alle 10:39
Mercoledė, 16/06/2010
Ciao a tutti
ho sviluppato una chat in java riferendomi a varie parti di codice prese su internet.
Tutto funziona, nel senso che con due pc connessi in rete, riesco a vedere i msg che invio e che l'altro pc invia a me, ma purtroppo solo sulla console di Eclipse.

Il mio problema č infatti rappresentato dal non riuscire a far visualizzare i messaggi che ricevo dall'altro pc sulla JtextArea della Chat.
Ho provato diverse alternative ma nessuna valida  

Vi posto il codice:

CLASSE SERVER RUNNER
Codice sorgente - presumibilmente Java

  1. codice:package SimpleChat;
  2.  
  3.  
  4. public class SimpleChatRunServer {
  5.         public static void main(String[] args) {
  6.                 SimpleChatServer ss=new SimpleChatServer();
  7.         try{
  8.                 ss.start();
  9.         }catch(Exception e){
  10.                 e.printStackTrace();
  11.         }
  12.  
  13.         }
  14. }



CLASSE SERVER

Codice sorgente - presumibilmente Java

  1. codice:package SimpleChat;
  2. import java.net.*;
  3. import java.util.Iterator;
  4. import java.io.*;
  5.  
  6.  
  7. public class SimpleChatServer {
  8.         private int clientPort;
  9.         private ServerSocket serverSocket;
  10.        
  11.         public void start() throws IOException{
  12.                 Socket client;
  13.                 serverSocket= new ServerSocket(7777);
  14.                 getServerInfo();
  15.  
  16.                 //ciclo infinito in ascolto di eventuali client
  17.                 while(true){
  18.                 client=startListening();
  19.                 getClientInfo(client);
  20.                 startListeningSingleClient(client);            
  21.                 }
  22.         }
  23.        
  24.         private void startListeningSingleClient(Socket client){
  25.                 Thread t=new Thread(new ParallelServer (client));
  26.                 t.start();
  27.         }              
  28.                
  29.        
  30.         public class ParallelServer implements Runnable{
  31.                 Socket client;
  32.                 BufferedReader is;
  33.                 DataOutputStream os;
  34.                
  35.                 //metodo costruttore
  36.                 public ParallelServer(Socket client){
  37.                         this.client=client;
  38.                         try{
  39.                                 //creo oggetti x stream in e out
  40.                                 is= new BufferedReader(new InputStreamReader(client.getInputStream()));//in entrata
  41.                                 os= new DataOutputStream (client.getOutputStream());//in uscita
  42.                         }catch(IOException e){
  43.                                 e.printStackTrace();
  44.                         }
  45.                 }
  46.  
  47.                 @Override
  48.                 public void run() {
  49.                         try {
  50.                                 while(true){
  51.                                         sendMessage(receiveMessage(is),is,os,client);
  52.                                 }
  53.                         } catch (Exception e) {
  54.                                 e.printStackTrace();
  55.                         }
  56.                 }
  57.         }
  58.        
  59.         public void getServerInfo(){
  60.                 InetAddress indirizzo=serverSocket.getInetAddress();
  61.                 String server=indirizzo.getHostAddress();
  62.                 int port=serverSocket.getLocalPort();
  63.                 System.out.println("In ascolto Server: " + server  + " porta: " + port);
  64.        
  65.         }
  66.  
  67.         public void getClientInfo(Socket client){
  68.                 //info sul client che ha effettuato la chiamata
  69.                 InetAddress address=client.getInetAddress();
  70.                 //String indirizzoClient=address.toString();
  71.                 String clientName=address.getHostName();
  72.                 clientPort=client.getPort();
  73.                 System.out.println("In chiamata client: " + clientName + " porta: " +  clientPort + " indirizzo: " + address);
  74.         }
  75.        
  76.         public Socket startListening() throws IOException{
  77.                 System.out.println("In attesa di chiamata dal client... ");
  78.                 return serverSocket.accept();
  79.         }
  80.        
  81.         public String receiveMessage(BufferedReader is)throws IOException{
  82.                 String strReceived=is.readLine();
  83.                 System.out.println("Il Client ha inviato: " + strReceived);
  84.                 return strReceived;
  85.         }
  86.         public void sendMessage(String recMsg, BufferedReader is, DataOutputStream os, Socket client) throws IOException{
  87.                 System.out.println("chiamo il metodo [broadcastMessage] con recMsg= " + recMsg);
  88.                 broadcastMessage(recMsg,client);
  89.         }
  90.        
  91.         private void broadcastMessage(String recMsg, Socket cl) throws IOException{
  92.                 if(!recMsg.equals("NOGOODUSER")){
  93.                         new DataOutputStream(cl.getOutputStream()).writeBytes(recMsg + "\n");
  94.                 }
  95.         }
  96.  
  97.         public void close(InputStream is,OutputStream os, Socket client) throws IOException{
  98.                 System.out.println("chiamata close");
  99.                 os.close();
  100.                 is.close();
  101.                 System.out.println("chiusura client: " + client.getInetAddress().getHostName() + " su porta: " + clientPort);
  102.                 client.close();
  103.         }
  104.        
  105. }



CLASSE CLIENT

Codice sorgente - presumibilmente Java

  1. codice:package SimpleChat;
  2. import java.net.*;
  3. import java.io.*;
  4.  
  5. public class SimpleChatClient {
  6.         private DataOutputStream os;
  7.         private BufferedReader is;
  8.         private Socket socket;
  9.         private int porta;
  10.        
  11.         public void start(String ipServer,int porta) throws IOException{
  12.                 //Connessione della socket con il server
  13.                 System.out.println("Tentativo di connessione con server: " + "[" + ipServer + "]" + " su porta: "+ "["+ porta +"]");
  14.                 socket = new Socket (ipServer,porta);
  15.                
  16.                 //Stream di Byte da passare al Socket
  17.                 os= new DataOutputStream (socket.getOutputStream());//in uscita
  18.                 is= new BufferedReader(new InputStreamReader(socket.getInputStream()));//in entrata
  19.         }
  20.        
  21.         public void sendMessage(String strMsg)throws IOException{
  22.                 System.out.println("Client scrive: "+ strMsg);
  23.                 os.writeBytes(strMsg + '\n');
  24.                
  25.         }
  26.        
  27.         public String receiveMessage()throws IOException{
  28.                 return is.readLine();
  29.         }
  30.        
  31.         public void close ()throws IOException{
  32.                 System.out.println("Chiusura client e  stream");
  33.                 os.close();
  34.                 is.close();
  35.                 socket.close();
  36.         }
  37. }



CLASSE GUI

Codice sorgente - presumibilmente Java

  1. codice:package SimpleChat;
  2.  
  3. import java.awt.BorderLayout;
  4. import javax.swing.JPanel;
  5. import javax.swing.JFrame;
  6. import java.awt.Dimension;
  7. import javax.swing.JScrollPane;
  8. import java.awt.Rectangle;
  9. import java.io.DataInputStream;
  10. import java.io.DataOutputStream;
  11. import java.io.IOException;
  12. import java.net.Socket;
  13.  
  14. import javax.swing.JDialog;
  15. import javax.swing.JOptionPane;
  16. import javax.swing.JTextArea;
  17. import javax.swing.JLabel;
  18. import javax.swing.JTextField;
  19. import javax.swing.SwingConstants;
  20. import javax.swing.JButton;
  21.  
  22. public class SimpleChatGUI extends JFrame {
  23.  
  24.         private static final long serialVersionUID = 1L;
  25.         private JPanel jCP_SimpleChatGUI = null;
  26.         private JScrollPane jSP_Chat = null;
  27.         private JTextArea jTxtA_Chat = null;
  28.         private JLabel jLbl_Server = null;
  29.         private JLabel jLbl_Nick = null;
  30.         private JLabel jLbl_Msg = null;
  31.         private JTextField jTxtF_Server = null;
  32.         private JTextField jTxtF_NickName = null;
  33.         private JTextField jTxtF_Msg = null;
  34.         private JButton jBto_EntraInChat = null;
  35.         private JButton jBto_Invia = null;
  36.         private SimpleChatServer server;
  37.         private SimpleChatClient client;
  38.         private static final int serverPort=7777;
  39.         private String strLastText;
  40.         private String strServerMsg;
  41.         private String strReceived;
  42.         private boolean isClientConnected;
  43.         /**
  44.          * This is the default constructor
  45.          */
  46.         public SimpleChatGUI() {
  47.                 super();
  48.                 initialize();
  49.                 //istanzia un client di tipo SimpleChatClient
  50.                 client=new SimpleChatClient();
  51.         }
  52.  
  53.         /**
  54.          * This method initializes this
  55.          *
  56.          * @return void
  57.          */
  58.         private void initialize() {
  59.                 this.setSize(514, 401);
  60.                 this.setResizable(false);
  61.                 this.setContentPane(getJCP_SimpleChatGUI());
  62.                 this.setTitle("Simple Chat v. 1.0");
  63.         }
  64.  
  65.        
  66.         private JPanel getJCP_SimpleChatGUI() {
  67.                 if (jCP_SimpleChatGUI == null) {
  68.                         jLbl_Msg = new JLabel();
  69.                         jLbl_Nick = new JLabel();
  70.                         jLbl_Server = new JLabel();
  71.                         jCP_SimpleChatGUI = new JPanel();
  72.                         jSP_Chat = new JScrollPane();
  73.                         jTxtA_Chat = new JTextArea();
  74.                         jBto_EntraInChat = new JButton();
  75.                         jTxtF_Server = new JTextField();
  76.                         jTxtF_NickName = new JTextField();
  77.                         jTxtF_Msg = new JTextField();
  78.                         jBto_Invia = new JButton();
  79.                        
  80.                         jCP_SimpleChatGUI.setLayout(null);
  81.                         jLbl_Msg.setText("Inserisci il tuo messaggio:");
  82.                         jLbl_Msg.setBounds(new Rectangle(14, 337, 152, 20));
  83.                         jLbl_Nick.setText("Inserisci NickName:");
  84.                         jLbl_Nick.setBounds(new Rectangle(14, 311, 152, 20));
  85.                         jLbl_Server.setText("Inserisci indirizzo Server:");
  86.                         jLbl_Server.setBounds(new Rectangle(14, 284, 150, 20));
  87.                         jSP_Chat.setBounds(new Rectangle(14, 14, 482, 257));
  88.                         jBto_EntraInChat.setBounds(new Rectangle(373, 310, 124, 22));
  89.                         jBto_EntraInChat.setText("Entra In Chat");
  90.                        
  91.                         //Click tasto [Entra in Chat]
  92.                         jBto_EntraInChat.addActionListener(new java.awt.event.ActionListener() {
  93.                                 public void actionPerformed(java.awt.event.ActionEvent e) {
  94.                        
  95.                                         if (jBto_EntraInChat.getText()=="Entra In Chat"){
  96.                                                 joinToChat();
  97.                                         }else{
  98.                                                 disconnect();
  99.                                         }
  100.                                        
  101.                                 }
  102.                         });
  103.                        
  104.                         jTxtF_Server.setBounds(new Rectangle(175, 282, 188, 22));
  105.                         jTxtF_NickName.setBounds(new Rectangle(175, 310, 188, 22));
  106.                         jTxtF_Msg.setBounds(new Rectangle(175, 336, 188, 22));
  107.                         jBto_Invia.setText("Invia Msg");
  108.                         jBto_Invia.setBounds(new Rectangle(373, 336, 124, 22));
  109.                         jBto_Invia.addActionListener(new java.awt.event.ActionListener() {
  110.                                 public void actionPerformed(java.awt.event.ActionEvent e) {
  111.                                         if (jTxtF_Msg.equals("")) return;
  112.                                         try{
  113.                                                 client.start(jTxtF_Server.getText(), serverPort);
  114.                                                 client.sendMessage(jTxtF_Msg.getText());
  115.                                                 //Operatore ternario:
  116.                                                 //variabile = (espr-booleana) ? espr1 : espr2;
  117.                                                 //se il valore della espr-booleana č true si assegna a variabile il valore di
  118.                                                 //espr1; altrimenti si assegna a variabile il valore di espr2.
  119.                                                 strLastText=jTxtA_Chat.getText().equals("")?"":jTxtA_Chat.getText()+"\n";
  120.                                                 jTxtA_Chat.setText(strLastText+ jTxtF_NickName.getText()+ " scrive: " + jTxtF_Msg.getText()+"\n");
  121.                                                 jTxtF_Msg.setText("");
  122.                                         }catch(Exception ex){
  123.                                                 ex.printStackTrace();
  124.                                         }
  125.                                 }
  126.                         });
  127.                        
  128.                        
  129.                         jSP_Chat.setViewportView(jTxtA_Chat);
  130.                         jCP_SimpleChatGUI.add(jSP_Chat, null);
  131.                         jCP_SimpleChatGUI.add(jLbl_Server, null);
  132.                         jCP_SimpleChatGUI.add(jLbl_Nick, null);
  133.                         jCP_SimpleChatGUI.add(jLbl_Msg, null);
  134.                         jCP_SimpleChatGUI.add(jTxtF_Server, null);
  135.                         jCP_SimpleChatGUI.add(jTxtF_NickName, null);
  136.                         jCP_SimpleChatGUI.add(jTxtF_Msg, null);
  137.                         jCP_SimpleChatGUI.add(jBto_EntraInChat, null);
  138.                         jCP_SimpleChatGUI.add(jBto_Invia, null);
  139.                        
  140.                 }
  141.                 return jCP_SimpleChatGUI;
  142.         }
  143.         public void joinToChat(){
  144.                 //Controlla che sia stato inserito un indirizzo x il server
  145.                 if(jTxtF_Server.getText().equals("")){
  146.                         jTxtF_Server.setText("192.168.0.1");
  147.                 }
  148.                 //Controlla che sia stato inserito un nickName
  149.                 if (jTxtF_NickName.getText().equals("")){
  150.                         JOptionPane.showMessageDialog(this,"Inserisci prima un NickName!","Attenzione",2);
  151.                         return;
  152.                 }
  153.                 try {
  154.                         //System.out.println("Invocazione del metodo [start] da classe: [SimpleChatClient]");
  155.                         client.start(jTxtF_Server.getText(),serverPort);
  156.                        
  157.                         //System.out.println("Invocazione del metodo [sendMessage] da classe: [SimpleChatClient]");
  158.                         client.sendMessage("~"+jTxtF_NickName.getText());
  159.                        
  160.                         //System.out.println("Invocazione del metodo [receiveMessage] da classe: [SimpleChatClient]");
  161.                         strServerMsg=jTxtF_NickName.getText()+ " " + client.receiveMessage();
  162.                         //jTxtA_Chat.setText(strServerMsg);
  163.                         //System.out.println(strServerMsg);
  164.                        
  165.                         jBto_EntraInChat.setText("Disconnetti");
  166.                         jBto_Invia.setEnabled(true);
  167.                         isClientConnected=true;
  168.                         System.out.println("Lancio [startReceivedThread()] da classe: [SimpleChatClient]");
  169.                         startReceivedThread();
  170.                 } catch (IOException e) {
  171.                         e.printStackTrace();
  172.                         System.out.println("" + e.getMessage());
  173.                 }
  174.         }
  175.        
  176.         private void disconnect(){
  177.                 try{
  178.                         client.start(jTxtF_Server.getText(),serverPort);
  179.                         client.sendMessage("^"+jTxtF_NickName.getText());
  180.                         strLastText=jTxtA_Chat.getText().equals("")?"":jTxtA_Chat.getText()+"\n";
  181.                         jTxtA_Chat.setText(strLastText+ jTxtF_NickName.getText()+ " ha abbandonato la chat!!!" + "\n");
  182.                         jTxtF_NickName.setText("");
  183.                         jTxtF_Msg.setText("");
  184.                         jBto_EntraInChat.setText("Entra In Chat");
  185.                         jBto_Invia.setEnabled(false);
  186.                         client.close();
  187.                         isClientConnected=false;
  188.                 }catch(Exception ex){
  189.                         ex.printStackTrace();
  190.                 }
  191.         }
  192.         private void startReceivedThread(){
  193.                 ParallelClient toRun= new ParallelClient();
  194.                 Thread msgClientThread= new Thread(toRun);
  195.                 msgClientThread.start();
  196.         }  
  197.  
  198.         public class ParallelClient implements Runnable{
  199.  
  200.                 @Override
  201.                 public void run() {
  202.                         String strLastText;
  203.                         String strReceived;
  204.                         while(isClientConnected){
  205.                                         try {
  206.                                                
  207.                                                 strReceived=client.receiveMessage();
  208.                                                 //Nb: se la Stringa strReceived=null => che il client si č disconnesso dal server
  209.                                                 if(strReceived==null){
  210.                                                         continue;
  211.                                                 }
  212.                                                 strLastText=jTxtA_Chat.getText().equals("")?"":jTxtA_Chat.getText()+"\n";
  213.                                                 jTxtA_Chat.setText(strLastText+ strReceived);
  214.        
  215.                                         } catch (IOException e) {
  216.                                                 e.printStackTrace();
  217.                                         }
  218.                         }
  219.                 }
  220.                
  221.         }
  222. }  //  @jve:decl-index=0:visual-constraint="10,10"


Mi aiutate per favore?
Grazie

PM Quote
Avatar
paoloricciuti (Ex-Member)
Pro


Messaggi: 137
Iscritto: 27/04/2010

Segnala al moderatore
Postato alle 16:39
Mercoledė, 16/06/2010
Giusto una cosa. Al posto di fare setText() sulla JTextArea usa append(). Comunque se ti serve dai un'occhiata ai sorgenti di JChat:

http://www.pierotofy.it/pages/sorgenti/dettagli/18515-JChat/

PM Quote
Avatar
Java5 (Ex-Member)
Rookie


Messaggi: 23
Iscritto: 19/10/2009

Segnala al moderatore
Postato alle 17:24
Mercoledė, 16/06/2010
Ciao
Grazie per il consiglio, avevo gia provato con il metodo append ma non funziona lo stesso.
Secondo altri pareri il problema sta nell'utilizzo dei comandi System.out.println() che mi espongono i msg ricevuti dagli altri client nella finestra di sistema di eclipse. Dovrei sostituire a questi i comandi: Settext o append per visualizzare direttamente i msg nella jtextArea.

PS:
La tua chat l'ho scaricata proprio questa mattina, per cercare di capire dove eventualmente sbagliavo e ne approfitto per farti anche i complimenti.
Carina, essenziale e funzionale.
Un ottimo esempio da cui prendere spunto.
Grazie ancora.
Java5

PM Quote
Avatar
paoloricciuti (Ex-Member)
Pro


Messaggi: 137
Iscritto: 27/04/2010

Segnala al moderatore
Postato alle 20:31
Mercoledė, 16/06/2010
Prova a fare come dicono loro. In effetti cosė dovrebbe funzionare.

P.S. grazie dei complimenti.

PM Quote