RETOUR | Exemple Java |
Construction d'une applet de lecture automatique de l'heure
Le programme serveur import java.net.* ; import java.io.* ; public class ServeurExemple3 { public static void main(String [] args) { ServerSocket srv ; int port = 5555 ; try { srv = new ServerSocket(port) ; System.out.println("Serveur Ok") ; while ( true ) { System.out.println("En attente") ; Socket connexion = srv.accept() ; System.out.println("Connexion") ; InputStream is = connexion.getInputStream() ; DataInputStream dis = new DataInputStream(is) ; String s = dis.readUTF() ; System.out.println(s) ; connexion.close() ; } } catch(IOException e) { } } } L'applet cliente import java.applet.Applet ; import java.awt.* ; import java.net.* ; public class Exemple5 extends Applet { private Label lb ; private String host ; public void init() { URL url = getDocumentBase() ; host = url.getHost() ; setLayout(new GridLayout(2,1,10,10)); add(lb = new Label("",Label.CENTER)); ThreadExemple5 te5 = new ThreadExemple5(host,lb) ; te5.start() ; } } Classe Thread de l'applet cliente import java.awt.* ; import java.net.* ; import java.io.* ; public class ThreadExemple5 extends Thread { private Label lb ; private String host ; public ThreadExemple5(String s,Label l) { lb = l ; host = s ; } public void run() { boolean bRun = true ; while ( bRun) { Socket s ; int port = 5555 ; try { s = new Socket(host,port) ; InputStream is = s.getInputStream() ; DataInputStream ois = new DataInputStream(is) ; int hr = ois.readInt() ; int mn = ois.readInt() ; int sc = ois.readInt() ; int ml = ois.readInt() ; lb.setText("Heure sur "+host+ " : "+hr+":"+mn+ ":"+sc+":"+ml) ; ois.close() ; } catch (UnknownHostException uhe) { bRun = false ; lb.setText(uhe.toString()) ; } catch (IOException ioe) { bRun = false ; lb.setText(ioe.toString()) ; } ; try { sleep(1000) ; } catch (Exception e) { } ; } } }
Remarques, erreurs |