|  RETOUR | Exemple Java | 
| Construction d'une applet de lecture de l'heure sur un serveur 
 
 Le programme serveur import java.net.* ;
import java.io.* ;
import java.util.* ;
public class ServeurExemple4 {
  public static void main(String [] args) {
    ServerSocket srv ;
    int port = 5555 ;
    try {
      srv = new ServerSocket(port) ;
      System.out.println("Serveur Ok") ;
      while ( true ) {
        Socket connexion = srv.accept() ;
        OutputStream os = connexion.getOutputStream() ;
        DataOutputStream oos = new DataOutputStream(os) ;
        GregorianCalendar gc = new GregorianCalendar() ;
        oos.writeInt((int) gc.get(Calendar.HOUR)) ;
        oos.writeInt((int) gc.get(Calendar.MINUTE)) ;
        oos.writeInt((int) gc.get(Calendar.SECOND)) ;
        oos.writeInt((int) gc.get(Calendar.MILLISECOND)) ;
        connexion.close() ; } }
    catch(IOException e) { }
    }
  }          
 L'applet cliente import java.applet.Applet ;
import java.awt.* ;
import java.awt.event.* ;
import java.net.* ;
import java.io.* ;
import java.util.* ;
public class Exemple4 extends Applet
                      implements ActionListener {
  private Button ok ;
  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));
    add(ok = new Button("Heure sur "+host));
    ok.addActionListener(this) ;
    }
  public void actionPerformed(ActionEvent e) {
    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(hr+":"+mn+":"+sc+":"+ml) ;
      repaint() ;
      ois.close() ; }
    catch (UnknownHostException uhe) {
      lb.setText(uhe.toString()) ; } 
    catch (IOException ioe) {
      lb.setText(ioe.toString()) ; } ;
    } 
  }           
 Remarques, erreurs | |