Skip to content
This repository was archived by the owner on Sep 10, 2018. It is now read-only.

Commit 2e60d5f

Browse files
TakiguchiTakiguchi
authored andcommitted
Ajout boucle pour connexion de plusieurs clients
1 parent da99e2d commit 2e60d5f

File tree

1 file changed

+60
-19
lines changed

1 file changed

+60
-19
lines changed
Lines changed: 60 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,66 @@
11
package fr.imie.formations.serveur;
2+
23
import java.io.IOException;
34
import java.net.ServerSocket;
45
import java.net.Socket;
56

6-
public class Serveur {
7-
public static void main(String[] args) {
8-
// TODO Auto-generated method stub
9-
ServerSocket hostServer;
10-
try {
11-
12-
13-
hostServer = new ServerSocket(8080);
14-
System.out.println("serveur disponnible sur le port 8080");
15-
// attente de la connexion d’un client
16-
Socket socket = hostServer.accept();
17-
System.out.print("connexion d'un client");
18-
} catch (IOException e) {
19-
// TODO Auto-generated catch block
20-
e.printStackTrace();
21-
}
22-
23-
24-
}
7+
public class Serveur implements Runnable {
8+
/**
9+
* Point d'entrée.
10+
*
11+
* @param args
12+
*/
13+
public static void main( String[] args ) {
14+
Serveur serveur = new Serveur( 8082 );
15+
Thread th = new Thread( serveur );
16+
th.start();
17+
}
18+
19+
/*
20+
* Attributs
21+
*/
22+
private int port;
23+
private ServerSocket socketServeur;
24+
private Socket socket;
25+
private int nbClients;
26+
private boolean flagFonctionnement;
27+
28+
/**
29+
* Constructeur
30+
*
31+
* @param pPort
32+
* Le port d'écoute du serveur.
33+
*/
34+
public Serveur( final int pPort ) {
35+
port = pPort;
36+
nbClients = 0;
37+
flagFonctionnement = true;
38+
39+
try {
40+
socketServeur = new ServerSocket( port );
41+
} catch ( final IOException e ) {
42+
e.printStackTrace();
43+
new RuntimeException( "Erreur lors de la création du serveur." );
44+
}
45+
}
46+
47+
/**
48+
* Fonctionnement du serveur.
49+
*/
50+
@Override
51+
public void run() {
52+
try {
53+
System.out.println( "Serveur démarré, écoute sur le port " + port );
54+
while ( flagFonctionnement ) {
55+
socket = socketServeur.accept();
56+
System.out.println( "Nouveau client (" + nbClients + ")" );
57+
nbClients++;
58+
59+
socket.close();
60+
}
61+
} catch ( final IOException e ) {
62+
e.printStackTrace();
63+
}
64+
System.out.println( "Serveur arrêté" );
65+
}
2566
}

0 commit comments

Comments
 (0)