====== Client et Serveur TCP en Java ======
Serveur TCP :
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public final class MainServer {
static PrintStream out = System.out;
public static void main(String[] args) throws ClassNotFoundException {
int port = 8888;
ServerSocket socket = null;
try {
// Création de la socket (en écoute sur le port 8888)
socket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
out.println("Listening on port " + port + "...");
boolean running = true;
Socket client = null;
while (running) {
try {
// Attend la connexion d'un client
client = socket.accept();
out.println("New client...");
// Flux d'entrée et sortie
ObjectInputStream inputStream = new ObjectInputStream(
client.getInputStream());
ObjectOutputStream outputStream = new ObjectOutputStream(
client.getOutputStream());
// Lecture du message du client
String message = (String) inputStream.readObject();
out.println("Message from " + client.getInetAddress() + ": "
+ message);
// Traitement de la requête
if (!message.equals("stop")) {
outputStream.writeObject("Yes, I'm alive!");
} else {
running = false;
outputStream.writeObject("Ok, I'm shutting down.");
}
// Fermeture des flux
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Fermeture de la connexion client
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
// Fermeture de la socket
socket.close();
out.println("Shutting down...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client TCP :
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public final class MainClient {
static PrintStream out = System.out;
public static void main(String[] args) throws ClassNotFoundException {
if (args.length != 2) {
out.println("Usage: java MainClient [server address] [message]");
System.exit(1);
}
Socket socket = null;
try {
// Connexion au serveur
socket = new Socket(args[0], 8888);
// Flux sortie
ObjectOutputStream outputStream = new ObjectOutputStream(
socket.getOutputStream());
// Envoi du message au serveur
outputStream.writeObject(args[1]);
// Flux d'entrée
ObjectInputStream inputStream = new ObjectInputStream(
socket.getInputStream());
// Lecture de la réponse
String message = (String) inputStream.readObject();
out.println("Response from " + socket.getInetAddress() + ": "
+ message);
// Fermeture des flux
outputStream.close();
inputStream.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Fermeture de la connexion réseau
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}