Esempio di una semplice applicazione
La seguente applicazione realizzata con le tre tecniche di comunicazione (Socket, RPC, RMI) consiste in un server che può fornire due tipi di servizi a un client che si connette ad esso: la data e l'ora di sistema. Il seguente esempio hal'obiettivo di mostrare quanto detto nel paragrafo 1.3, senza badare ad ulteriori dettagli implementativi.
Socket
Implementazione del client (Client.java):
import java.io.*;import java.net.*;public class Client{public static void main( String[] args ) throws IOException{Socket socket = null;PrintStream out = null;DataInputStream in = null;String server = "127.0.0.1";try {socket = new Socket( server, 4321 );out = new PrintStream( socket.getOutputStream() );in = new DataInputStream( socket.getInputStream() );}catch( UnknownHostException e ){System.err.println("Impossibile collegarsi al server " + server );System.exit(1);}catch( IOException e ){System.err.println( "Impossibile comunicare con il server " + server );System.exit(1);}DataInputStream stdIn = new DataInputStream( System.in );String fromServer;String fromUser;while( ( fromServer = in.readLine() ) != null ){System.out.println( "Server: " + fromServer );if( fromServer.equals( "fine collegamento" ) )break;System.out.print( "> " );fromUser = stdIn.readLine();if( fromUser != null ){System.out.println("Client: " + fromUser);out.println(fromUser);}}out.close();in.close();stdIn.close();socket.close();}}
Leave a Comment