RETOUR | Exemple Java |
Construction d'une applet d'envoi de messages
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.awt.event.* ; import java.net.* ; import java.io.* ; public class Exemple3 extends Applet implements ActionListener { private Button ok ; private TextField tf1 ; private String host ; public void init() { setLayout(new GridLayout(3,1,10,10)); add(new Label("Message",Label.CENTER)); add(tf1 = new TextField(10)); add(ok = new Button("Envoyer")); ok.addActionListener(this) ; URL url = getDocumentBase() ; host = url.getHost() ; } public void actionPerformed(ActionEvent e) { Socket s ; int port = 5555 ; try { s = new Socket(host,port) ; OutputStream os = s.getOutputStream() ; DataOutputStream dos = new DataOutputStream(os) ; dos.writeUTF(tf1.getText()) ; dos.close() ; } catch (UnknownHostException uhe) { System.out.println(uhe) ; } catch (IOException ioe) { System.out.println(ioe) ; } ; } }
Remarques, erreurs |