Socket in Java con Gui

Tethys

Nuovo Utente
26 Gen 2018
3
0
1
40
Buonasera,
mi sto imbattendo nello sviluppo di una semplice chat (uno a uno) in java. Mi serve perchè devo sviluppare un progetto universitario. Ho scritto tutto il codice, ma le due interfacce (che hanno una textarea, una textfield ed un button) non si parlano:(. Se qualcuno riuscisse a darmi qualche suggerimento ne sarei grata. Copio il codice qui sotto.
Codice:
Classe per il server:
import java.awt.EventQueue;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class chat_server {
    public JFrame frmServer;
    public  static JTextField msg_text = new JTextField();;
    public static  JTextArea msg_area = new JTextArea();
    public  static JButton msg_send = new JButton("Send");
    /**
    * Launch the application.
    */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    chat_server window = new chat_server();
                    window.frmServer.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        String msgin="";
        try {
            ss = new ServerSocket(6789); //diamo la porta del server
            s= ss.accept();//mi metto in ascolto sulla porta che ho aperto
            ss.close();//per fare una connessione uno a uno
            din= new DataInputStream(s.getInputStream());
            dout=new DataOutputStream(s.getOutputStream());
          
            while(!msgin.equals("exit")) {
                msgin=din.readUTF();
                msg_area.append("\n"+msgin);;// visualizziamo il messaggio dal client
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
 
    static ServerSocket ss;
    static Socket s;
    static DataInputStream din;
    static DataOutputStream dout;
 
    /**
    * Create the application.
    */
    public chat_server() {
        initialize();
    }
    /**
    * Initialize the contents of the frame.
    */
    private void initialize() {
        frmServer = new JFrame();
        frmServer.setTitle("Server");
        frmServer.setBounds(100, 100, 450, 300);
        frmServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmServer.getContentPane().setLayout(null);
      
        JTextArea msg_area = new JTextArea();
        msg_area.setBounds(12, 12, 400, 150);
        frmServer.getContentPane().add(msg_area);
      
        msg_text = new JTextField();
        msg_text.setBounds(12, 188, 290, 35);
        frmServer.getContentPane().add(msg_text);
        msg_text.setColumns(10);
      
        JButton msg_send = new JButton("Send");
        msg_send.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String msgout="";
                try {
                  
                    msgout=msg_text.getText().trim();
                    dout.writeUTF("Server: "+msgout);//mandiamo il messaggio del server al client
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        msg_send.setFont(new Font("Arial", Font.BOLD, 14));
        msg_send.setBounds(325, 188, 95, 35);
        frmServer.getContentPane().add(msg_send);
    }
}

Classe per il Client:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Font;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class chat_client {
    public JFrame frmClient;
    public  static JTextField msg_text = new JTextField();;
    public static  JTextArea msg_area = new JTextArea();
    public  static JButton msg_send = new JButton("Send");
    /**
    * Launch the application.
    */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    chat_client window = new chat_client();
                    window.frmClient.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        String msgin="";
        try {
            s=new Socket(InetAddress.getLocalHost(),6789);// indirizzo ip locale perche lanciamo client e server dalla stessa macchina
            din=new DataInputStream(s.getInputStream());
            dout=new DataOutputStream(s.getOutputStream());
          
            while (!msgin.equals("exit")) {
                msgin=din.readUTF();
                msg_area.append("\n"+msgin);;
            }
          
          
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    static Socket s;
    static DataInputStream din;
    static DataOutputStream dout;
    /**
    * Create the application.
    */
    public chat_client() {
        initialize();
    }
    /**
    * Initialize the contents of the frame.
    */
    private void initialize() {
        frmClient = new JFrame();
        frmClient.setTitle("Client");
        frmClient.setBounds(100, 100, 450, 300);
        frmClient.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmClient.getContentPane().setLayout(null);
      
      
        msg_area.setBounds(12, 12, 400, 150);
        frmClient.getContentPane().add(msg_area);
      
      
        msg_send.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String msgout="";
                try {
                  
                    msgout=msg_text.getText().trim();
                    dout.writeUTF("Client: "+msgout);//mandiamo il messaggio del server al client
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        msg_send.setFont(new Font("Arial", Font.BOLD, 14));
        msg_send.setBounds(325, 188, 95, 35);
        frmClient.getContentPane().add(msg_send);
      
      
        msg_text.setBounds(12, 188, 290, 35);
        frmClient.getContentPane().add(msg_text);
        msg_text.setColumns(10);
    }
}
Spero nei vostri suggerimenti.
Vi ringrazio anticipatamente. Buon Pomeriggio a tutti ;)
 
Ultima modifica di un moderatore:

Max 1

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
29 Feb 2012
4.449
338
83
@Tethys
Da regolamento del forum, come tutti noi sei tenuta ad usare il tag
code.gif
quando posti del codice, oppure la funzione codice dalla barra degli strumenti
box inserisci 2.png.JPG

Inoltre ti prego di leggere attentamente il regolamento generale del forum e quello di sezione dove posti
Grazie
Per questa volta te lo sistemo io ma mi raccomando per il futuro
 

Tethys

Nuovo Utente
26 Gen 2018
3
0
1
40
Ciao Max, scusami questa cosa mi era sfuggita...ti ringrazio per la correzione...ho sbagliato anche la sezione?:(..
 
Discussioni simili
Autore Titolo Forum Risposte Data
trattorino socket su cloud Cloud Computing e Cloud Server 2
G [PHP] Socket server in loop infinito errori PHP 2
L ios socket read/write tcp Sviluppo app per iOS 0
I Socket > Cominicazione fra due host Flash 3
P Impossibile completare immediatamente l'operazione sul socket non a blocchi. PHP 1
P Socket bind non funziona PHP 1
P Leggere un socket PHP 4
P Non capisco se invio il socket PHP 2
M Timeout su socket Java 2
A problema con socket PHP 15
K Gestione ricezione dati da socket e polling PHP 15
C errore Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' MySQL 0
G buffer di socket e file PHP 0
L php e socket PHP 3
L java api_google Javascript 0
F NetBeans problema creazione progetto Java Windows e Software 0
Z [java] bufferizzare stream audio da mic Java 1
L java + Api di google Javascript 1
A [Cerchiamo] [Retribuito/a] "Java Solution Architect" Offerte e Richieste di Lavoro e/o Collaborazione 1
F Script java elenco alfabetico non funziona Javascript 3
C Serializzazione in java Java 1
M AIUTO ESERCIZIO JAVA Javascript 1
M Ripasso Java Offerte e Richieste di Lavoro e/o Collaborazione 0
F [OFFRO - RETRIBUITO] Sviluppatori JAVA Offerte e Richieste di Lavoro e/o Collaborazione 0
L leggere RGB di un pixel dello schermo in java Java 1
I Creazione programmino JAVA Offerte e Richieste di Lavoro e/o Collaborazione 0
F Aiuto java script Javascript 2
T [Java] tipi generici con esempio pratico Java 1
J File audio in java Java 0
V [JAVA] come integrare un software scritto in java su una pagina web? Java 4
C Java client / server Java 0
F [OFFRO][RETRIBUITO] PROGRAMMATORE JAVA Offerte e Richieste di Lavoro e/o Collaborazione 0
C [Java] testare un metodo con Junit Java 1
A [Java] caricare un url esterno senza utilizzo di iframe Java 0
S [OFFRO] Debug delle tue applicazioni Java Offerte e Richieste di Lavoro e/o Collaborazione 1
L [Java] Aggiungere elementi ad array JSON Java 0
B [Java] Paginazione in risposta HTTP Java 0
A [Java]Date diminuite di un giorno su db MySQL Java 0
K [Java] aiuto switch case Java 1
P [Java] limite destro di un JFrame Java 5
D [Java] far partire JProgressBar all'apertura di un JFrame Java 1
N [java con eclipse]metodo ricorsivo che accetta in ingresso un char e restituisce un int Java 0
A Verifica validità data in Java Java 2
L [Java] Errore json conversione Java 0
Drago73 [Java] leggere/scrivere txt server Java 0
M [Javascript] Java card Java 0
serena.cerutti posizioni aperte: PhP, Java, .Net Offerte e Richieste di Lavoro e/o Collaborazione 0
N [Java]problema jasper report dopo compilazione file .jar Java 0
N [Java] Piccolo jform per calcolo totale da 2 campi i double Java 0
N [Java] jbutton con funzioni Java 2

Discussioni simili