Visualizzazione dei risultati da 1 a 10 su 10

Discussione: [JAVA]Socket...

  1. #1

    [JAVA]Socket...

    Ciao a tutti!

    Mi stò avvicinando alla programmazione client server e vorrei provare a scrivere una applicazione che utilizza le socket per trasmettere degli oggetti tramite la rete LAN.
    Ho iniziato a guardare i tutorial sul mio sito preferito (java.sun.com ) e ho provato a buttare giù un paio di righe di codice.
    Ho implementato una classe dal nome Message (implements serializable)il cui costruttore crea un oggetto contenente una stringa:
    codice:
    public Message (String message ) {
        this.message = message;
      }
    Poi ho creato una classe Server che entra in un loop infinito in cui si occupa di accettare una connessione in entrata (serverSocket server = new ServerSocket(1428) e di lanciare un thread per ogni client accettato.
    Ogni thread ha il compito di leggere il messaggio del client, stamparlo sullo standard output e mandargli un oggetto che contiene la stringa "messaggio ricevuto".
    Il fatto è che dopo aver ricevuto il primo messaggio e spedito il messaggio predefinito, mi esce con un errore, mentre il client continua a funzionare.
    Qualcuno ha idea di cosa possa essere?Il codice allegato è corretto?
    Mi sapreste dare dei consigli su come procedere per scambiare dei messaggi tra server e client facendo in modo che il server aspetti un messaggio prima di continuare con la sua esecuzione?
    Vi allego degli stralci del codice che ho scritto(metto solo le parti significative):

    Server:
    codice:
      public static final int porta = 1428;
    
      public Server () throws IOException {
        ServerSocket server = new ServerSocket (porta);
        while (true) {
          Socket client = server.accept();
          System.out.println("Connection Accepted");
          Thread connection = new ServerThread ( client.getInputStream() , client.getOutputStream() );
          connection.start();
        }
    Thread del Server:
    codice:
    public class ServerThread extends Thread {
      private ObjectInputStream input;
      private ObjectOutputStream output;
    
      public ServerThread (InputStream is, OutputStream os) {
      	try {
      		input = new ObjectInputStream ( is );
     	 	output = new ObjectOutputStream ( os );
     	 } catch ( Exception e) {
     	 	System.err.println ("Errore nel costruttore del Thread del Server: " + e );
     	 }
      }
    
      public void run () {
      	try {
       		while (true) {
       			System.out.println ("Leggo il messaggio in input e la stampo a video");
       			String Messaggio = ( ((Message) input.readObject() ).getMessage() );
       	 		System.out.println(Messaggio);
       	 		System.out.println ("Provo a inviare un messaggio");
    	   	 	Message conferma = new Message ("Messaggio ricevuto!");
     	  	 	output.writeObject (conferma);
      	 	 	output.flush();
      	 	 	System.out.println ("Svuotato il buffer di output,adesso riparto!");  	 	 	
      	 	}
      	} catch (Exception e) {
      		System.err.println ("Errore nel Thread del Server: "+ e );
      	}
     }

  2. #2
    Utente di HTML.it L'avatar di floyd
    Registrato dal
    Apr 2001
    Messaggi
    3,837
    se metti anche il messaggio di errore ...
    avrai sbagliato a mandare un messaggio che il server non si aspetta

  3. #3
    Scusate...me ne sono dimenticato (scusate anche il ritardo mostruoso con cui rispondo.. )
    Ecco l'errore che mi viene restituito:

    Errore nel Thread del Server: java.io.StreamCourptedException

    Che può essere?
    Mi sapete consigliare un buon tutorial sulle socket?
    Quello sul sito della sun fa abbastanza schifetto..
    Tnx

    Alder

  4. #4
    Utente di HTML.it L'avatar di floyd
    Registrato dal
    Apr 2001
    Messaggi
    3,837
    se puoi posta anche il codice del client
    per mandare un testo usa un DataOutputStream

  5. #5
    Allego tutto...tanto è solo una prova....nulla di importante....
    Ecco tutto il codice:

    Message
    codice:
    import java.io.Serializable;
    
    public class Message implements Serializable {
      private String message;
    
      public Message (String msg) {
        message = msg;
      }
    
      public String getMessage() {
        return message;
      }
      
      public void setMessage (String msg) {
        message = msg;
      }
    }
    Client
    codice:
    import java.net.*;
    import java.io.*;
    
    class Client {
      public static void main (String [] args){
        try {
        Client chatclient = new Client();
        } catch (Exception e) {
          System.err.println("Errore di I/O :" + e);
        }
      }
    
      public static final int porta = 1428;
      public Message message = new Message ("");
    
      public Client () throws Exception {
        //Apro una socket per leggere e scrivere
        Socket client = new Socket (InetAddress.getLocalHost() , porta);
        System.out.println("Connesso con il server!");    
        ObjectInputStream ois;
        ObjectOutputStream oos;
        
        //Ora leggo e scrivo
        while (true) {
          oos = new ObjectOutputStream ( client.getOutputStream() );
          EasyIn easy = new EasyIn ();
          System.out.print("Digita il tuo messaggio: ");
          message = new Message ( easy.readString() );
          oos.writeObject(message);
    	  oos.flush();
          ois = new ObjectInputStream ( client.getInputStream() );
          String INmessage = ( ((Message) ois.readObject()).getMessage() );
          System.out.println( INmessage );
    /*      ois.close();
          System.out.println ("Ho chiuso lo stream di Input");
          oos.close();
          System.out.println ("Ho chiuso lo stream di Output"); 
    */
        }
      }
    }
    Server
    codice:
    import java.net.*;
    import java.io.*;
    
    class Server {
      public static void main (String [] args){
        try {
        Server chatserver = new Server();
        } catch (IOException e) {
          System.err.println("Errore di IO" + e);
        }
      }
    
      public static final int porta = 1428;
    
      public Server () throws IOException {
        ServerSocket server = new ServerSocket (porta);
        while (true) {
          Socket client = server.accept();
          System.out.println("Connection Accepted");
          Thread connection = new ServerThread ( client.getInputStream() , client.getOutputStream() );
          connection.start();
        }
      }
    }
    Server Thread
    codice:
    import java.net.*;
    import java.io.*;
    
    public class ServerThread extends Thread {
      private ObjectInputStream input;
      private ObjectOutputStream output;
    
      public ServerThread (InputStream is, OutputStream os) {
      	try {
      		input = new ObjectInputStream ( is );
     	 	output = new ObjectOutputStream ( os );
     	 } catch ( Exception e) {
     	 	System.err.println ("Errore nel costruttore del Thread del Server: " + e );
     	 }
      }
    
      public void run () {
      	try {
       		while (true) {
       			System.out.println ("Leggo il messaggio in input e la stampo a video");
       			String Messaggio = ( ((Message) input.readObject() ).getMessage() );
       	 		System.out.println(Messaggio);
       	 		System.out.println ("Provo a inviare un messaggio");
    	   	 	Message conferma = new Message ("Messaggio ricevuto!");
     	  	 	output.writeObject (conferma);
      	 	 	output.flush();
      	 	 	System.out.println ("Svuotato il buffer di output,adesso riparto!");
      	 	 	//output.close();
      	 	 	//input.close();
      	 	}
      	} catch (Exception e) {
      		System.err.println ("Errore nel Thread del Server: "+ e );
      	}
      }
    }
    EasyIn
    codice:
    // Simple input from the keyboard for all primitive types. ver 1.0
    // Copyright (c) Peter van der Linden, May 5 1997.
    //      corrected error message 11/21/97
    //
    // The creator of this software hereby gives you permission to:
    // 1. copy the work without changing it
    // 2. modify the work providing you send me a copy which I can
    //      use in any way I want, including incorporating into this work.
    // 3. distribute copies of the work to the public by sale, lease,
    //      rental, or lending
    // 4. perform the work
    // 5. display the work
    // 6. fold the work into a funny hat and wear it on your head.
    //
    // This is not thread safe, not high performance, and doesn't tell EOF.
    // It's intended for low-volume easy keyboard input.
    // An example of use is:
    //      EasyIn easy = new EasyIn();
    //      int i = easy.readInt();
    // reads an int from System.in
    //      float f = easy.readFloat();
    // reads a float from System.in
    
    import java.io.*;
    import java.util.*;
    
    class EasyIn {
    static InputStreamReader is = new InputStreamReader( System.in );
    static BufferedReader br = new BufferedReader( is );
    StringTokenizer st;
    
    StringTokenizer getToken() throws IOException { 
    String s = br.readLine();
    return new StringTokenizer(s);
    }
    
    boolean readBoolean() {
    try {
    st = getToken();
    return new Boolean(st.nextToken()).booleanValue(); } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readBoolean"); return false;
    }
    }
    
    byte readByte() {
    try {
    st = getToken();
    return Byte.parseByte(st.nextToken());
    } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readByte");
    return 0;
    }
    }
    
    short readShort() {
    try {
    st = getToken();
    return Short.parseShort(st.nextToken()); } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readShort");
    return 0;
    }
    }
    
    int readInt() {
    try {
    st = getToken();
    return Integer.parseInt(st.nextToken()); } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readInt");
    return 0;
    }
    }
    
    long readLong() {
    try {
    st = getToken();
    return Long.parseLong(st.nextToken());
    } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readLong");
    return 0L;
    }
    }
    
    float readFloat() {
    try {
    st = getToken();
    return new Float(st.nextToken()).floatValue(); } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readFloat");
    return 0.0F;
    }
    }
    
    double readDouble() {
    try {
    st = getToken();
    return new Double(st.nextToken()).doubleValue(); } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readDouble");
    return 0.0;
    }
    }
    
    char readChar() {
    try {
    String s = br.readLine();
    return s.charAt(0);
    } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readChar");
    return 0;
    }
    }
    
    String readString() {
    try {
    return br.readLine();
    } catch (IOException ioe) {
    System.err.println("IO Exception in EasyIn.readString");
    return "";
    }
    }
    
    // This method is just here to test the class 
    public static void main (String args[]){ 
    EasyIn easy = new EasyIn();
    
    System.out.print("enter char: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readChar() ); 
    
    System.out.print("enter String: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readString() ); 
    
    System.out.print("enter boolean: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readBoolean() ); 
    
    System.out.print("enter byte: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readByte() ); 
    
    System.out.print("enter short: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readShort() ); 
    
    System.out.print("enter int: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readInt() ); 
    
    System.out.print("enter long: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readLong() ); 
    
    System.out.print("enter float: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readFloat() ); 
    
    System.out.print("enter double: ");
    System.out.flush();
    System.out.println("You entered: " + easy.readDouble() ); }
    
    }
    Grazie per la disponibilità

    Alder

  6. #6
    Utente di HTML.it L'avatar di floyd
    Registrato dal
    Apr 2001
    Messaggi
    3,837
    metti
    oos = new ObjectOutputStream ( client.getOutputStream() );
    ois = new ObjectInputStream ( client.getInputStream() );
    fuori dal ciclo

  7. #7
    Così facendo il client aspetta all'infinito di avere qualcosa in input da leggere...
    mmmm
    Alder

  8. #8
    Se ti interessa posso mandarti un progetto che avevo fatto per l'uni, puoi adattare facilmente tutto per le tue esigenze.
    www.ntnet.it/xp <- Prova in flash
    utenti.tripod.it/guate <- Un mio 'viaggio' in guatemala
    www.aspcode.it <- Risorsa gratuita su ASP
    www.mmorpgitalia.it <- Il motore in php del network é una mia creazione, se qualcuno vuole dare una mano é il benvenuto.

  9. #9
    Mi faresti una cortesia.
    Gli do un occhio e vedo che posso fare.
    Ti ho mandato via pvt la mia mail.
    Grazie

    Alder

  10. #10
    Ti è arrivata la mail?
    www.ntnet.it/xp <- Prova in flash
    utenti.tripod.it/guate <- Un mio 'viaggio' in guatemala
    www.aspcode.it <- Risorsa gratuita su ASP
    www.mmorpgitalia.it <- Il motore in php del network é una mia creazione, se qualcuno vuole dare una mano é il benvenuto.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.