Oppure

Loading
16/06/10 8:39
Java5
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:package SimpleChat;


public class SimpleChatRunServer {
	public static void main(String[] args) {
		SimpleChatServer ss=new SimpleChatServer();
	try{
		ss.start();
	}catch(Exception e){
		e.printStackTrace();
	}

	}
}



CLASSE SERVER

codice:package SimpleChat;
import java.net.*;
import java.util.Iterator;
import java.io.*;


public class SimpleChatServer {
	private int clientPort;
	private ServerSocket serverSocket;
	
	public void start() throws IOException{
		Socket client;
		serverSocket= new ServerSocket(7777);
		getServerInfo();

		//ciclo infinito in ascolto di eventuali client
		while(true){
		client=startListening();
		getClientInfo(client);
		startListeningSingleClient(client);		
		}
	}
	
	private void startListeningSingleClient(Socket client){
		Thread t=new Thread(new ParallelServer (client));
		t.start();
	}		
		
	
	public class ParallelServer implements Runnable{
		Socket client;
		BufferedReader is;
		DataOutputStream os;
		
		//metodo costruttore
		public ParallelServer(Socket client){ 
			this.client=client;
			try{
				//creo oggetti x stream in e out
				is= new BufferedReader(new InputStreamReader(client.getInputStream()));//in entrata
				os= new DataOutputStream (client.getOutputStream());//in uscita
			}catch(IOException e){
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			try {
				while(true){
					sendMessage(receiveMessage(is),is,os,client);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void getServerInfo(){
		InetAddress indirizzo=serverSocket.getInetAddress();
		String server=indirizzo.getHostAddress();
		int port=serverSocket.getLocalPort();
		System.out.println("In ascolto Server: " + server  + " porta: " + port);
	
	}

	public void getClientInfo(Socket client){
		//info sul client che ha effettuato la chiamata
		InetAddress address=client.getInetAddress();
		//String indirizzoClient=address.toString();
		String clientName=address.getHostName();
		clientPort=client.getPort();
		System.out.println("In chiamata client: " + clientName + " porta: " +  clientPort + " indirizzo: " + address);
	}
	
	public Socket startListening() throws IOException{
		System.out.println("In attesa di chiamata dal client... ");
		return serverSocket.accept();
	}
	
	public String receiveMessage(BufferedReader is)throws IOException{
		String strReceived=is.readLine();
		System.out.println("Il Client ha inviato: " + strReceived);
		return strReceived;
	}
	public void sendMessage(String recMsg, BufferedReader is, DataOutputStream os, Socket client) throws IOException{
		System.out.println("chiamo il metodo [broadcastMessage] con recMsg= " + recMsg);
		broadcastMessage(recMsg,client);
	} 
	
	private void broadcastMessage(String recMsg, Socket cl) throws IOException{
		if(!recMsg.equals("NOGOODUSER")){
			new DataOutputStream(cl.getOutputStream()).writeBytes(recMsg + "\n");
		}
	}

	public void close(InputStream is,OutputStream os, Socket client) throws IOException{
		System.out.println("chiamata close");
		os.close();
		is.close();
		System.out.println("chiusura client: " + client.getInetAddress().getHostName() + " su porta: " + clientPort);
		client.close();
	}
	
}



CLASSE CLIENT

codice:package SimpleChat;
import java.net.*;
import java.io.*;

public class SimpleChatClient {
	private DataOutputStream os;
	private BufferedReader is; 
	private Socket socket;
	private int porta;
	
	public void start(String ipServer,int porta) throws IOException{
		//Connessione della socket con il server
		System.out.println("Tentativo di connessione con server: " + "[" + ipServer + "]" + " su porta: "+ "["+ porta +"]");
		socket = new Socket (ipServer,porta);
		
		//Stream di Byte da passare al Socket
		os= new DataOutputStream (socket.getOutputStream());//in uscita
		is= new BufferedReader(new InputStreamReader(socket.getInputStream()));//in entrata
	}
	
	public void sendMessage(String strMsg)throws IOException{
		System.out.println("Client scrive: "+ strMsg);
		os.writeBytes(strMsg + '\n');
		
	}
	
	public String receiveMessage()throws IOException{
		return is.readLine();
	}
	
	public void close ()throws IOException{
		System.out.println("Chiusura client e  stream");
		os.close();
		is.close();
		socket.close();
	}
}



CLASSE GUI

codice:package SimpleChat;

import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Dimension;
import javax.swing.JScrollPane;
import java.awt.Rectangle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JButton;

public class SimpleChatGUI extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jCP_SimpleChatGUI = null;
	private JScrollPane jSP_Chat = null;
	private JTextArea jTxtA_Chat = null;
	private JLabel jLbl_Server = null;
	private JLabel jLbl_Nick = null;
	private JLabel jLbl_Msg = null;
	private JTextField jTxtF_Server = null;
	private JTextField jTxtF_NickName = null;
	private JTextField jTxtF_Msg = null;
	private JButton jBto_EntraInChat = null;
	private JButton jBto_Invia = null;
	private SimpleChatServer server;
	private SimpleChatClient client;
	private static final int serverPort=7777;
	private String strLastText;
	private String strServerMsg;
	private String strReceived;
	private boolean isClientConnected;
	/**
	 * This is the default constructor
	 */
	public SimpleChatGUI() {
		super();
		initialize();
		//istanzia un client di tipo SimpleChatClient
		client=new SimpleChatClient();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(514, 401);
		this.setResizable(false);
		this.setContentPane(getJCP_SimpleChatGUI());
		this.setTitle("Simple Chat v. 1.0");
	}

	
	private JPanel getJCP_SimpleChatGUI() {
		if (jCP_SimpleChatGUI == null) {
			jLbl_Msg = new JLabel();
			jLbl_Nick = new JLabel();
			jLbl_Server = new JLabel();
			jCP_SimpleChatGUI = new JPanel();
			jSP_Chat = new JScrollPane();
			jTxtA_Chat = new JTextArea();
			jBto_EntraInChat = new JButton();
			jTxtF_Server = new JTextField();
			jTxtF_NickName = new JTextField();
			jTxtF_Msg = new JTextField();
			jBto_Invia = new JButton();
			
			jCP_SimpleChatGUI.setLayout(null);
			jLbl_Msg.setText("Inserisci il tuo messaggio:");
			jLbl_Msg.setBounds(new Rectangle(14, 337, 152, 20));
			jLbl_Nick.setText("Inserisci NickName:");
			jLbl_Nick.setBounds(new Rectangle(14, 311, 152, 20));
			jLbl_Server.setText("Inserisci indirizzo Server:");
			jLbl_Server.setBounds(new Rectangle(14, 284, 150, 20));
			jSP_Chat.setBounds(new Rectangle(14, 14, 482, 257));
			jBto_EntraInChat.setBounds(new Rectangle(373, 310, 124, 22));
			jBto_EntraInChat.setText("Entra In Chat");
			
			//Click tasto [Entra in Chat]
			jBto_EntraInChat.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
			
					if (jBto_EntraInChat.getText()=="Entra In Chat"){
						joinToChat();
					}else{
						disconnect();
					}
					
				}
			});
			
			jTxtF_Server.setBounds(new Rectangle(175, 282, 188, 22));
			jTxtF_NickName.setBounds(new Rectangle(175, 310, 188, 22));
			jTxtF_Msg.setBounds(new Rectangle(175, 336, 188, 22));
			jBto_Invia.setText("Invia Msg");
			jBto_Invia.setBounds(new Rectangle(373, 336, 124, 22));
			jBto_Invia.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if (jTxtF_Msg.equals("")) return;
					try{
						client.start(jTxtF_Server.getText(), serverPort);
						client.sendMessage(jTxtF_Msg.getText());
						//Operatore ternario:
						//variabile = (espr-booleana) ? espr1 : espr2;
						//se il valore della espr-booleana è true si assegna a variabile il valore di
						//espr1; altrimenti si assegna a variabile il valore di espr2.
						strLastText=jTxtA_Chat.getText().equals("")?"":jTxtA_Chat.getText()+"\n";
						jTxtA_Chat.setText(strLastText+ jTxtF_NickName.getText()+ " scrive: " + jTxtF_Msg.getText()+"\n");
						jTxtF_Msg.setText("");
					}catch(Exception ex){
						ex.printStackTrace();
					}
				}
			});
			
			
			jSP_Chat.setViewportView(jTxtA_Chat);
			jCP_SimpleChatGUI.add(jSP_Chat, null);
			jCP_SimpleChatGUI.add(jLbl_Server, null);
			jCP_SimpleChatGUI.add(jLbl_Nick, null);
			jCP_SimpleChatGUI.add(jLbl_Msg, null);
			jCP_SimpleChatGUI.add(jTxtF_Server, null);
			jCP_SimpleChatGUI.add(jTxtF_NickName, null);
			jCP_SimpleChatGUI.add(jTxtF_Msg, null);
			jCP_SimpleChatGUI.add(jBto_EntraInChat, null);
			jCP_SimpleChatGUI.add(jBto_Invia, null);
			
		}
		return jCP_SimpleChatGUI;
	}
	public void joinToChat(){
		//Controlla che sia stato inserito un indirizzo x il server
		if(jTxtF_Server.getText().equals("")){
			jTxtF_Server.setText("192.168.0.1");
		}
		//Controlla che sia stato inserito un nickName
		if (jTxtF_NickName.getText().equals("")){
			JOptionPane.showMessageDialog(this,"Inserisci prima un NickName!","Attenzione",2);
			return;
		}
		try {
			//System.out.println("Invocazione del metodo [start] da classe: [SimpleChatClient]");
			client.start(jTxtF_Server.getText(),serverPort);
			
			//System.out.println("Invocazione del metodo [sendMessage] da classe: [SimpleChatClient]");
			client.sendMessage("~"+jTxtF_NickName.getText());
			
			//System.out.println("Invocazione del metodo [receiveMessage] da classe: [SimpleChatClient]");
			strServerMsg=jTxtF_NickName.getText()+ " " + client.receiveMessage();
			//jTxtA_Chat.setText(strServerMsg);
			//System.out.println(strServerMsg);
			
			jBto_EntraInChat.setText("Disconnetti");
			jBto_Invia.setEnabled(true);
			isClientConnected=true;
			System.out.println("Lancio [startReceivedThread()] da classe: [SimpleChatClient]");
			startReceivedThread();
		} catch (IOException e) {
			e.printStackTrace(); 
			System.out.println("" + e.getMessage());
		}
	}
	
	private void disconnect(){
		try{
			client.start(jTxtF_Server.getText(),serverPort);
			client.sendMessage("^"+jTxtF_NickName.getText());
			strLastText=jTxtA_Chat.getText().equals("")?"":jTxtA_Chat.getText()+"\n";
			jTxtA_Chat.setText(strLastText+ jTxtF_NickName.getText()+ " ha abbandonato la chat!!!" + "\n");
			jTxtF_NickName.setText("");
			jTxtF_Msg.setText("");
			jBto_EntraInChat.setText("Entra In Chat");
			jBto_Invia.setEnabled(false);
			client.close();
			isClientConnected=false;
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	private void startReceivedThread(){
		ParallelClient toRun= new ParallelClient();
		Thread msgClientThread= new Thread(toRun);
		msgClientThread.start();
	}  

	public class ParallelClient implements Runnable{

		@Override
		public void run() {
			String strLastText;
			String strReceived;
			while(isClientConnected){
					try {
						
						strReceived=client.receiveMessage();
						//Nb: se la Stringa strReceived=null => che il client si è disconnesso dal server
						if(strReceived==null){
							continue; 
						}
						strLastText=jTxtA_Chat.getText().equals("")?"":jTxtA_Chat.getText()+"\n";
						jTxtA_Chat.setText(strLastText+ strReceived);
	
					} catch (IOException e) {
						e.printStackTrace(); 
					}
			}
		}
		
	}
}  //  @jve:decl-index=0:visual-constraint="10,10"  

Mi aiutate per favore?
Grazie
aaa
16/06/10 14:39
paoloricciuti
Giusto una cosa. Al posto di fare setText() sulla JTextArea usa append(). Comunque se ti serve dai un'occhiata ai sorgenti di JChat:

pierotofy.it/pages/sorgenti/dettagli/18515-JChat/
aaa
16/06/10 15:24
Java5
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
aaa
16/06/10 18:31
paoloricciuti
Prova a fare come dicono loro. In effetti così dovrebbe funzionare.

P.S. grazie dei complimenti.
aaa