Exemple Programmation Client/serveur
avec Socket TCP en java
1. Machine Serveur (socket TCP)
//classe TestServeurTCP
import java.io.*;
import java.net.*;
public class TestServeurTCP {
final static int port = 9632;
public static void main(String[] args) {
ServerSocket SocketServeur;
try {
SocketServeur = new ServerSocket(port);
System.out.println("Lancement du serveur");
Socket clientServiceSocket = null;
String request="";
//String reply;
while (true) {
try {
clientServiceSocket = SocketServeur.accept();
System.out.println("Connexion avec : " +clientServiceSocket.getInetAddress());
PrintWriter out = new PrintWriter(clientServiceSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(clientServiceSocket.getInputStream()));
while (true) {
request = in.readLine();
// Traitement à faire sur le serveur executer le service
// traiter request pour fournir reply
out.println("Le serveur a reçu le message suivant : " +request);
}
} catch (IOException e) {
System.out.println("Déconnexion client sur port "+ port);
System.exit(-1);
}
clientServiceSocket.close();
SocketServeur.close();
}
} catch (IOException e) {
System.out.println(" Port " +port + " non utilisable..!");
System.exit(-1);
}
}
}
1
2. Côté Client
//Client TCP en java
import java.net.*;
import java.io.*;
import javax.swing.JOptionPane;
public class TestClientTCP {
final static int port = 9632;
public static void main(String[] args) {
Socket socket;
DataInputStream userInput;
PrintStream theOutputStream;
String message;
try {
InetAddress serveur = InetAddress.getByName("localhost");
socket = new Socket(serveur, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
boolean stop= false;
while(!stop){
message = JOptionPane.showInputDialog("Entrez votre message ");
out.println(message);
System.out.println(in.readLine());
if (message.equalsIgnoreCase("stop")) stop = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}