Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Exemple inspiré du livre _Java in a Nutshell_
- import java.io.*;
- import java.net.*;
- public class MonServeurSimple {
- public final static int DEFAULT_PORT = 6789;
- protected int port;
- protected ServerSocket listen_socket;
- protected BufferedReader in;
- protected PrintStream out;
- // traitement des erreurs
- public static void fail(Exception e, String msg){
- System.err.println(msg + ": " + e);
- System.exit(1);
- }
- // Cree un serveur TCP : c'est un objet de la
- // classe ServerSocket
- // Puis lance l'ecoute du serveur.
- public MonServeurSimple(int port) {
- if (port == 0) port = DEFAULT_PORT;
- this.port = port;
- Socket client = null;
- try { listen_socket = new ServerSocket(port);
- System.out.println("Serveur en écoute sur le port:"+port);
- while(true) {
- client = listen_socket.accept();
- in = new BufferedReader(new
- InputStreamReader(client.getInputStream()));
- out = new
- PrintStream(client.getOutputStream());
- traitement();
- }
- } catch (IOException e) {
- fail(e, "Pb lors de l'écoute"); }
- finally { try {client.close();} catch (IOException e2) { } }
- }
- // Le lancement du programme :
- // - initialise le port d'écoute
- // - lance la construction du serveurTCP
- public static void main(String[] args) {
- int port = 0;
- if (args.length == 1) {
- try { port = Integer.parseInt(args[0]); }
- catch (NumberFormatException e) { port =
- 0; }
- }
- new MonServeurSimple(port);
- }
- public void traitement() {
- String line;
- StringBuffer revline;
- int len;
- try {
- for(;;) {
- // lit la ligne
- line = in.readLine();
- // Si cette ligne est vide,
- // le serveur se termine
- if (line == null) break;
- // sinon l'ecrit a l'envers
- len = line.length();
- revline = new StringBuffer(len);
- for(int i = len-1; i >= 0; i--)
- revline.insert(len-1-i, line.charAt(i));
- // et l'envoie dans la socket
- out.println(revline);
- }
- } catch (IOException e) { ; }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment