Travaux Pratiques
Sockets en Java
Exercice 1 (Sockets UDP)
Ecrire un serveur qui écoute qu’un client lui envoie un message puis il l’affiche.
Solution
Coté client :
package sockUDP;
/**
*
* @author ddiongue
*/
import [Link].*;
import [Link].*;
public class UDPEchoClient {
/*Adresse IP du serveur*/
private static InetAddress host;
//Port du serveur
private static final int PORT = 1234;
// Datagram Socket
private static DatagramSocket dtgrSocket;
//Emission/Réception des paquets UDP
private static DatagramPacket inPkt, outPkt;
//Mémoire tampon contenant les données
private static byte[] buff;
//Variable stockant le contenu du message
private static String msg = "", msgIn = "";
public static void main(String[] args)
{
try{
host = [Link]();
}
catch(UnknownHostException e){
[Link]("Host not found!");
[Link](1);
}
run();
}
private static void run(){
try{
dtgrSocket = new DatagramSocket();
BufferedReader userEntry;
userEntry = new BufferedReader(new
InputStreamReader([Link]));
do{
[Link]("Entrer le message !");
msg = [Link]();
if(){
outPkt = new DatagramPacket([Link](),
[Link](), host, PORT);
[Link](outPkt);
buff = new byte[256];
inPkt = new DatagramPacket(buff,
[Link]);
[Link](inPkt);
msgIn = new String([Link](), 0,
[Link]());
[Link]("Serveur: " + msgIn);
}
}while();
}
catch(IOException e){
[Link]();
}
finally{
[Link]();
}
}
}
1. Coté serveur :
package sockUDP;
/**
*
* @author ddiongue
*/
import [Link].*;
import [Link].*;
/*UDP server class.*/
public class UDPEchoServer {
/*port used by the server.*/
private static final int PORT = 1234;
/*the datagram socket specific to UDP.*/
private static DatagramSocket dgramSocket;
/*incoming and outgoing packets objects.*/
private static DatagramPacket inPkt, outPkt;
/*packet data buffer.*/
private static byte[] buffer;
public static void main(String[] args) {
[Link]("Opening port...\n");
try {
/*create the datagram socket*/
dgramSocket = new DatagramSocket(PORT);
} catch (SocketException e) {
/*handle potential exceptions.*/
[Link]("Error attach port!");
[Link](1);
}
run();
}
/*run() performs the main task of the server.*/
private static void run() {
try {
/*buffers for the messages to be sent and
received.*/
String msgIn, msgOut;
/*number of messages.*/
int numMsgs = 0;
do {
/*create the packet buffer.*/
buffer = new byte[256];
/*create the incoming packet.*/
inPkt = new DatagramPacket(buffer,
[Link]);
/*receive the packet from the client.*/
[Link](inPkt);
/*retrieve the sender’s IP address.*/
InetAddress cliAddress = [Link]();
/*retrieve the sender’s port number.*/
int cliPort = [Link]();
/*store the content of the message.*/
msgIn
= new String([Link](), 0,
[Link]());
[Link]("Message received.");
/*increment the message number.*/
numMsgs++;
/*generate the outgoing message.*/
msgOut = ("Msg " + numMsgs + ": " + msgIn);
/*create the outgoing packet.*/
outPkt = new DatagramPacket([Link](),
[Link](), cliAddress, cliPort);
/*send the outgoing packet to the client.*/
[Link](outPkt);
} while (true);
} catch (IOException e) {
[Link]();
} finally {
/*close the socket and release its resources.*/
[Link]();
}
}
}
Compiler et exécuter ces programmes sur deux machines distinctes.
Exercice 2
Coté serveur ([Link])
package sockTCP;
/**
*
* @author ddiongue
*/
import [Link].*;
import [Link].*;
/*TCP-based echo server*/
public class TCPEchoServer {
/*server socket*/
private static ServerSocket servSock;
/*server port*/
private static final int PORT = 1234;
public static void main(String[] args) {
[Link]("Opening port\n");
try {
/*Create the server socket*/
servSock = new ServerSocket(PORT);
} catch (SocketException e) {
/*handle potential exceptions*/
[Link]("Error attach port!");
[Link](1);
} catch (IOException e) {
/*handle potential exceptions*/
[Link]("Error create socket!");
[Link](1);
}
/*perform the echo service indefinitely*/
do {
run();
} while (true);
}
private static void run() {
/*data socket*/
Socket sock = null;
try {
/*listen for incoming connections*/
sock = [Link]();
/*create a socket buffer reader*/
BufferedReader in = new BufferedReader(
new
InputStreamReader([Link]()));
/*create the socket writer*/
PrintWriter out = new PrintWriter(
[Link](), true);
int numMsgs = 0;
/*read from the data socket*/
String msg = [Link]();
while () {
[Link]("Message received.");
numMsgs++;
[Link]("Message " + numMsgs + ": " + msg);
msg = [Link]();
}
[Link](numMsgs + " messages received.");
} catch (IOException e) {
[Link]();
} finally {
/*close the socket*/
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
Coté client ([Link])
/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sockTCP;
/**
*
* @author ddiongue
*/
import [Link].*;
import [Link].*;
public class TCPEchoClient {
/*server IP*/
private static InetAddress host;
/*server port*/
private static final int PORT = 1234;
public static void main(String[] args) {
[Link]("Opening port\n");
try {
/*create server IP address object*/
host = [Link]();
} catch (UnknownHostException e) {
[Link]("Host not found!");
[Link](1);
}
run();
}
private static void run() {
Socket sock = null;
try {
/*create data socket*/
sock = new Socket(host, PORT);
/*create socket reader and writer*/
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter(
[Link](), true);
/*Set up stream for user entry*/
BufferedReader reader
= new BufferedReader(new
InputStreamReader([Link]));
/*storage for message and response message*/
String msgOut, msgIn;
do {
[Link]("Entrer le message: ");
/*read user message*/
msgOut = [Link]();
/*send the message*/
[Link](msgOut);
/*read the response*/
msgIn = [Link]();
[Link]("SERVEUR> " + msgIn);
} while ();
} catch (IOException e) {
[Link]();
} finally {
/*close the data socket*/
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
Compiler et exécuter les programmes ci-dessus sur deux machines différentes
Exercice 3 : Serveur TCP multi-client
Pour cela on réalise d’abord un serveur mono-client ensuite le serveur multi-client sera en réalité
plusieurs threads exécutant chacun un serveur mono-client.
Code serveur mono-client ([Link])
package sockTCP;
/**
*
* @author ddiongue
*/
import [Link].*;
import [Link];
/*single-threaded server class*/
/*handles client communication*/
public class SingleTCPEchoServer extends Thread {
/*client data socket*/
private static Socket sock;
/*server port*/
private static final int PORT = 1234;
/*BufferReader used to read data from data socket*/
private BufferedReader in;
/*PrinterWriter used to write to the data socket*/
private PrintWriter out;
/*Constructor for the single threaded server*/
public SingleTCPEchoServer(Socket s)
throws IOException {
/*set the data socket*/
sock = s;
/*create the BufferReader from data socket*/
in = new BufferedReader(new InputStreamReader(
[Link]()));
/*create the PrintWriter for data socket*/
out = new PrintWriter(
[Link](), true);
/*If any of the above calls throws an exception,
the caller will close the socket.
Otherwise the thread will close it.*/
/*call the run() method*/
start();
}
/*run() method performs the actual task*/
public void run() {
try {
int numMessages = 0;
/*read message from the data socket (client)*/
String msg = [Link]();
/*verify if the message is BYE*/
while () {
[Link]("Message received.");
/*count the number of messages received*/
numMessages++;
/*send the reply message to the client*/
[Link]("Message " + numMessages
+ ": " + msg);
/*read the next message*/
msg = [Link]();
}
/*at this point BYE has been received*/
/*the server reports the number of received
messages*/
[Link](numMessages + " messages received.");
} catch (IOException e) {
[Link]();
} finally {
try {
[Link]("\n Closing connection");
/*close the data socket*/
[Link]();
} catch (IOException e) {
[Link]("Unable to disconnect!");
[Link](1);
}
}
} /*run()*/
}
package sockTCP;
/**
*
* @author ddiongue
*/
import [Link].*;
import [Link].*;
/*Class implementing the multi-threaded echo server.*/
/*This server receives a message from the clients
*and replies with the same message back.
*/
public class MultiTCPEchoServer {
/*The server socket is defined as a class member.*/
private static ServerSocket servSock;
/*The port number is defined as a member.*/
/*The server will listen on this port.*/
private static final int PORT = 1234;
/*Data socket is defined as a member.*/
/*Socket to be used for */
/*communication with the client.*/
Socket sock = null;
/*Constructor.*/
public MultiTCPEchoServer() {
}
/*The main function to be run
*when the server application stars.*/
public static void main(String[] args)
throws IOException {
[Link]("Opening port\n");
try {
/*Create the server socket to listen on PORT*/
servSock = new ServerSocket(PORT);
} catch (IOException e) {
/*Handles potential exceptions
*thrown while the server socket is created.*/
/*Most common exception is triggered
*when the chosen port is already used*/
[Link]("Port error!");
[Link](1);
}
/*At this point the server socket
*was successfully created.*/
try {
/*main server loop.*/
do {
/*Server accepts connections from client.*/
/*The Accept method blocks
*until a connection occurs.*/
Socket socket = [Link]();
try {
/*Create a single-threaded server.*/
/*This will handle the client.*/
new SingleTCPEchoServer(socket);
} catch (IOException e) {
/*Handle potential exceptions.*/
/*As the creation of the
*single-threaded server failed,
*communication with the client can not
start,
*so the data socket is closed.
*/
[Link]();
}
} while (true);
} finally {
/*When the server end its operation,
*the server socket is closed.
*/
[Link]();
}
}
}
Exercice 4
Le serveur attend de multiples requêtes du client. Le client envoie de multiples
requêtes au serveur. Le serveur répond par reçu.
Le serveur :
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sockets;
/**
*
* @author ddiongue
*/
public class Serveur
{
public static void main(String args[]) throws Exception {
String str;
ServerSocket ssoc;
ssoc = new ServerSocket(9999);
while(true)
{
[Link]("En attente..."); Socket soc =
[Link](); [Link]("Socket accepte");
InputStream is = [Link](); DataInputStream dis =
new DataInputStream(is);
[Link]("Lecture du socket"); str = [Link]();
[Link]("RECU: "+str);
[Link]();
}
} }
Le client :
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sockets;
/**
*
* @author ddiongue
*/
public class Client
{
static public void main(String args[]) throws Exception {
while(true)
{
DataInputStream in = new DataInputStream([Link]);
[Link]("> ");
[Link]();
String valeur=
[Link]();
Socket soc = new Socket([Link](),9999);
OutputStream os=[Link](); DataOutputStream dos=new
DataOutputStream(os);
[Link](valeur);
[Link]();
}
} }