Lato Server
e lato Clientcodice:package server5; import java.net.*; import java.io.*; public class Server { public static void main(String[] args) { Socket client=null; ServerSocket server=null; try { server=new ServerSocket(11111); } catch(IOException e) { e.printStackTrace(); } while(true) { System.out.println("Attesa Connessione..."); try { client=server.accept(); } catch(IOException e) { System.out.println("connessione fallita"); System.exit(1); } System.out.println("Connessione da" + client); BufferedReader is=null; PrintStream os=null; try { is=new BufferedReader(new InputStreamReader(client.getInputStream())); BufferedOutputStream ob=new BufferedOutputStream(client.getOutputStream()); os= new PrintStream(ob,false);//per stampare il file String n=new String(is.readLine()); System.out.println("File: "+ n); FileInputStream file=new FileInputStream(n); DataInputStream ifile=new DataInputStream(file); String r=null; while((r=ifile.readLine())!=null) { os.println(r); } os.flush();os.close();is.close();client.close(); } catch(FileNotFoundException e) { System.out.println("File non trovato"); os.println("File non trovato"); os.flush();os.close(); } catch(Exception e) { e.printStackTrace(); } } } }
codice:package client4; import java.io.*; import java.net.*; /** * * @author Alessandro */ public class Client4 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Socket s=null; BufferedReader is=null; PrintStream os=null; try { s = new Socket("localhost",11111); is = new BufferedReader(new InputStreamReader(s.getInputStream())); os = new PrintStream(new BufferedOutputStream(s.getOutputStream())); }catch(IOException e) { System.out.println(e.getMessage()); System.exit(1); } //controllo argomenti if(args.length==0) { os.println("Missing name file!"); System.out.println("Manca argomento"); os.flush();os.close(); return; } try { is.close();s.close(); } catch(IOException e) { System.out.println(e.getMessage()); } //invio messaggio System.out.println("Sending..." + args[0]); os.println(args[0]);os.flush(); //stampa risposta dal server System.out.println("Attesa risposta dal server"); String line=null; try { while((line=is.readLine())!=null) { System.out.println("Messaggio: "+ line); } is.close();os.close();s.close(); } catch(IOException e) { System.out.println(e.getMessage()); } } }

Rispondi quotando