Buon Giorno e buon anno a tutti,sto facendo delle prove con i socket,lo so che mi massacrerete,volevo far si che quando al server arriva la parola tutto mi restituisca un oggetto.
Server:
e questo è il client:codice:private void button1ActionPerformed(java.awt.event.ActionEvent evt) { Thread t= new Thread(new startServer()); t.start(); } /** * @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(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Server.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 Server().setVisible(true); } }); } public class startServer implements Runnable { @Override public void run() { connessione(); comunica(); } public void comunica() { try { // do // { System.out.println("[3] - Aspetto un messaggio"); jTextArea2.append("[3] - Aspetto un messaggio \n"); letto = in.readLine(); System.out.println("[4] - Messaggio ricevuto "+letto); jTextArea2.append("[4] - Messaggio ricevuto \n"+letto); if (letto.equals("tutto")) { inviaArray(); }else{ String risposta = letto.toUpperCase(); System.out.println("[5] - Rispondo con: "+risposta); out.writeBytes(risposta+ "\n"); } // }while (!letto.toLowerCase().equals("esci")); { // System.out.println("[6] - Chiudo la connessione. "); // socketClient.close();//chiudo l aconnesione con // } } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } } public Socket connessione() { try { jTextArea2.append("[0] - Inizializzo il server \n"); //inizialaiziamo il servizio server = new ServerSocket(porta); jTextArea2.append("[1] - in ascolto sulla porta "+porta+"\n"); //mi metto in ascolto sulla porta che ho aperto socketClient = server.accept(); jTextArea2.append("[2] - Connesione stabilita con client! \n"); //server.close(); in= new DataInputStream(socketClient.getInputStream()); out = new DataOutputStream(socketClient.getOutputStream()); } catch (IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } return socketClient; } public void inviaArray() { ArrayList<String> prova = new ArrayList<String>();; try { String DATABASE_URL = "jdbc:ucanaccess:///OneDrive//Programmazione//Android//dati.mdb;password=gmpa;memory=false"; Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); Connection conn = DriverManager.getConnection(DATABASE_URL); System.out.println(conn); Statement s = conn.createStatement(); ResultSet rs = s.executeQuery("SELECT * FROM [tabripa]"); while (rs.next()) { prova.add(rs.getString("Nbusta")); prova.add(rs.getString("Nome")); } try { server.accept(); ObjectOutputStream objectOutput = new ObjectOutputStream(socketClient.getOutputStream()); objectOutput.writeObject(prova); } catch (IOException e) { e.printStackTrace(); } // System.out.println(arraydatiList.size()); // System.out.println(arraydatiList.get(1).getNbusta()); // System.out.println(arraydatiList.get(1).getNome()); /* // create a table String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0)); String createTable = "CREATE TABLE " + tableName + " (id Integer, name Text(32))"; s.execute(createTable); // enter value into table for(int i=0; i<25; i++) { String addRow = "INSERT INTO " + tableName + " VALUES ( " + String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + String.valueOf(Math.random()) + "')"; s.execute(addRow); } */ // Fetch table // drop the table // String dropTable = "DROP TABLE " + tableName; //s.execute(dropTable); // close and cleanup s.close(); conn.close(); } catch(Exception ex) { ex.printStackTrace(); } } } // Variables declaration - do not modify private java.awt.Button button1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextArea jTextArea2; // End of variables declaration }
Quando invio tutto il client mi restituisce:codice:public class Client { Socket mioSocket = null; int porta = 6789;//porta server DataInputStream in; DataOutputStream out; BufferedReader tastiera; String messaggio; public void comunica() { try { do { tastiera = new BufferedReader(new InputStreamReader(System.in)); System.out.print("[2] - Messaggio da inviare al server: "); messaggio = tastiera.readLine(); if (messaggio.equals("tutto")) { out.writeBytes(messaggio+"\n"); ArrayList<String> arrayBusta = new ArrayList<String>(); try { ObjectInputStream objectInput = new ObjectInputStream(mioSocket.getInputStream()); //Error Line! try { Object object = objectInput.readObject(); arrayBusta = (ArrayList<String>) object; for (int i = 0; i < arrayBusta.size(); i++) { // String get = arrayBusta.get(i); System.out.println(arrayBusta.get(i)); } } catch (ClassNotFoundException e) { System.out.println("The title list has not come from the server"); e.printStackTrace(); } } catch (IOException e) { System.out.println("The socket for reading the object has problem"); e.printStackTrace(); } }else{ System.out.println("[3] - Invio del"+messaggio); out.writeBytes(messaggio+"\n"); System.out.println("[4] - In attesa di una risposta...!"); String ricevuta = in.readLine(); System.out.println("[5] - Risposta del server: "+ricevuta); } }while (!messaggio.toLowerCase().equals("esci")); { } } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } public Socket connetti() { try { try { System.out.println("[0] - Provo a connettermi al server"); Socket mioSocket = new Socket(InetAddress.getLocalHost(),porta); System.out.println("[1] - Connesso!"); in = new DataInputStream(mioSocket.getInputStream()); out = new DataOutputStream(mioSocket.getOutputStream()); } catch (UnknownHostException ex) { System.err.println("Host Sconosciuto"); } } catch (Exception ex) { System.err.println("Impossibile stabilire connessione"); } return mioSocket; } public static void main(String[] args) { Client c = new Client(); c.connetti(); c.comunica(); } }
codice:Exception in thread "main" java.lang.NullPointerException at ProvaServerClient2.Client.comunica(Client.java:56) at ProvaServerClient2.Client.main(Client.java:117) C:\Users\Paolo\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 3 seconds)

Rispondi quotando