|
Voici la classe, pour le client, à utiliser avec le serveur du code sample précédent :
package client;
import java.io.*;
import java.net.*;
import java.lang.Integer;
public class MonClient {
private Socket maSocket;
private PrintWriter sortieSocket;
private InputStream entreeSocket;
private int port;
private String adresse;
public static void main(String[] args) {
MonClient client = new MonClient(args);
client.lancer();
}
MonClient(String[] args) {
maSocket = null;
sortieSocket = null;
entreeSocket = null;
port = 80;
adresse = "localhost";
if (args.length != 2) {
System.out
.println("\nSyntaxe : MonClient Adresse Port\nValeurs par defaut : localhost, 80");
} else {
adresse = args[0];
port = Integer.parseInt(args[1]);
}
}
public void lancer() {
try {
maSocket = new Socket(adresse, port); //connexion de la socket à distance
// Définition du Flux de Sortie de la Socket (Envoi)
sortieSocket = new PrintWriter(maSocket.getOutputStream(), true);
// Définition du Flux d’ entrée de la Socket (Reception)
entreeSocket = maSocket.getInputStream();
System.err.println("\nSocket connectee sur le port " + port
+ " vers l’hote " + adresse);
System.err
.println("Taper Aide pour plus d’infos, Ctrl + c pour Fermer");
} catch (UnknownHostException e) {
System.err.println("Hote inconnu localhost");
System.exit(1);
} catch (IOException e) {
System.err.println("Impossible de creer un flux de connexion");
System.exit(1);
}
// Entrée Standard
byte[] buffer = new byte[1024];
int read = 0;
FileOutputStream fOut = null;
try {
String fichier = "1.mp3";
sortieSocket.println(fichier);
fOut = new FileOutputStream("./recu/" + fichier);
while ((read = entreeSocket.read(buffer)) > 0) {
fOut.write(buffer, 0, read);
}
sortieSocket.close();
entreeSocket.close();
maSocket.close();
fOut.close();
} catch (IOException e) {
}
}
}
|