0% found this document useful (0 votes)
36 views4 pages

Correction TP4

This document contains code examples for implementing TCP and UDP sockets in Java. It includes code for a TCP server and client that allow clients to connect to the server and exchange messages. It also includes code for UDP clients and servers that can send and receive datagrams. The exercises demonstrate how to create threaded server applications, and how to modify the UDP client to prompt the user for input to send to the server.

Uploaded by

chadha hidri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views4 pages

Correction TP4

This document contains code examples for implementing TCP and UDP sockets in Java. It includes code for a TCP server and client that allow clients to connect to the server and exchange messages. It also includes code for UDP clients and servers that can send and receive datagrams. The exercises demonstrate how to create threaded server applications, and how to modify the UDP client to prompt the user for input to send to the server.

Uploaded by

chadha hidri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

U NIVERSITÉ DE J ENDO UBA

I NSTITUT S UPÉ RIEUR DE L’I NFORM ATIQUE DU K EF

TP 4 : "Sockets TCP et socket UDP"

Matière : Développement d’applications réparties Niveau : 3eme LSI


Responsable : Hanen Samaali A U : 2023 / 2024

Exercice 1 :
1. Classe seveur
import java.io.*;
import java.net.*;

public class Serveur {


public static void main(String[] args) {
int port = 5000;

try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Serveur en attente de connexions sur le port " +
port);

while (true) {
Socket clientSocket = serverSocket.accept();
ClientHandler clientHandler = new ClientHandler(clientSocket);
new Thread(clientHandler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class ClientHandler implements Runnable {


private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;

public ClientHandler(Socket socket) {


this.clientSocket = socket;
}

@Override
public void run() {
try {
in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);

out.println("C'est quoi votre nom ?");


String nom = in.readLine();
out.println("Enchanté, " + nom);

clientSocket.close();
1
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. Classe client
import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
String serverAddress = "localhost";
int serverPort = 5000;

try {
Socket socket = new Socket(serverAddress, serverPort);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader keyboardInput = new BufferedReader(new
InputStreamReader(System.in));

String message = in.readLine();


System.out.println("Serveur: " + message);

String nom = keyboardInput.readLine();


out.println(nom);

message = in.readLine();
System.out.println("Serveur: " + message);

socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Exercice 2 :
public class MultiThreadExample {
public static void main(String[] args) {
// Création et démarrage du premier thread pour "Bonjour !"
Thread bonjourThread = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println("Bonjour !");
try {
Thread.sleep(1000); // Pause d'une seconde (1000 millisecondes)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Création et démarrage du deuxième thread pour "Salut !"


Thread salutThread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Salut !");
try {
2
Thread.sleep(2000); // Pause de deux secondes (2000
millisecondes)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Démarrage des deux threads


bonjourThread.start();
salutThread.start();
}
}
Exercice 3 :
1. Classe serveur
import java.net.*;
import java.io.*;

public class ServeurUDP {


public static void main(String[] args) {
int serveurPort = 7777;

try {
// Création du socket UDP lié au port 7777
DatagramSocket socket = new DatagramSocket(serveurPort);

// Définition d'un tableau de 15 octets pour stocker les données reçues


byte[] buffer = new byte[15];

// Création d'un paquet pour recevoir les données


DatagramPacket receivedPacket = new DatagramPacket(buffer,
buffer.length);

System.out.println("Attente de réception d'un paquet...");

// Attente de la réception d'un paquet


socket.receive(receivedPacket);

// Récupération et affichage des données reçues


String message = new String(receivedPacket.getData(), 0,
receivedPacket.getLength());
System.out.println("Message reçu du client : " + message);

// Fermeture du socket
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. Classe client
import java.net.*;
import java.io.*;

public class ClientUDP {


public static void main(String[] args) {
try {
InetAddress serveurAddress = InetAddress.getByName("localhost");
int serveurPort = 7777;
3
// Création du paquet de données
byte[] data = "Hello".getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length,
serveurAddress, serveurPort);

// Création du socket UDP


DatagramSocket socket = new DatagramSocket();

// Envoi du paquet au serveur


socket.send(packet);

System.out.println("Message envoyé au serveur : Hello");

// Fermeture du socket
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Exercice 4 :
import java.net.*;
import java.io.*;
import java.util.Scanner;

public class ClientUDP {


public static void main(String[] args) {
try {
InetAddress serveurAddress = InetAddress.getByName("localhost");
int serveurPort = 7777;

Scanner scanner = new Scanner(System.in);

// Saisie du message à envoyer au serveur


System.out.print("Saisissez un message à envoyer au serveur : ");
String message = scanner.nextLine();

// Création du paquet de données


byte[] data = message.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length,
serveurAddress, serveurPort);

// Création du socket UDP


DatagramSocket socket = new DatagramSocket();

// Envoi du paquet au serveur


socket.send(packet);

System.out.println("Message envoyé au serveur : " + message);

// Fermeture du socket
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

You might also like