0% ont trouvé ce document utile (0 vote)
35 vues39 pages

Réseaux et Sockets en Java: Guide M2

Le document traite des concepts fondamentaux des réseaux en Java, y compris les couches de protocole, les adresses IP, et les sockets. Il aborde également la création de connexions client-serveur, l'utilisation de proxys, et les classes Java pertinentes pour la gestion des adresses et des connexions. Des exemples de code illustrent comment interagir avec des sockets et récupérer des informations réseau.

Transféré par

yansahkadanzanbe
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
35 vues39 pages

Réseaux et Sockets en Java: Guide M2

Le document traite des concepts fondamentaux des réseaux en Java, y compris les couches de protocole, les adresses IP, et les sockets. Il aborde également la création de connexions client-serveur, l'utilisation de proxys, et les classes Java pertinentes pour la gestion des adresses et des connexions. Des exemples de code illustrent comment interagir avec des sockets et récupérer des informations réseau.

Transféré par

yansahkadanzanbe
Copyright
© All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Réseau avec Java:

M2 informatique
Protocoles et réseaux

I) Introduction
† Les couches

M2 internet H. Fauconnier 2

1
Couche Internet
† Datagramme IPv4

M2 internet H. Fauconnier 3

Couche transport
† TCP
„ Mode connecté, flot bidirectionnel, sûr,
contrôle de la congestion
„ Téléphone

† UDP
„ Mode non connecté, messages, sans
garantie, déséquencement
„ Poste
M2 internet H. Fauconnier 4

2
Adresses internet
† Adresse IP: adresse réseau + site sur
le réseau
† Exemple:

M2 internet H. Fauconnier 5

Classe d’adresses Internet

M2 internet H. Fauconnier 6

3
Connexion
† Adresse IP +port
† Ports réservés
† Ports libres

M2 internet H. Fauconnier 7

Quelques ports
Protocol Port Protocol Protocol Port Protocol
echo 7 TCP/UDP
whois 43 TCP
discard 9 TCP/UDP
finger 79 TCP
daytime 13 TCP/UDP
FTP data 20 TCP HTTP 80 TCP
FTP 21 TCP POP3 110 TCP
SSH 22 TCP NNTP 119 TCP
telnet 23 TCP
IMAP 143 TCP
smtp 25 TCP
109
time 37 TCP/UDP RMI Registry TCP
9

M2 internet H. Fauconnier 8

4
Proxys

M2 internet H. Fauconnier 9

Comment travailler avec un


proxy?
† Régler le navigateur… les applets du navigateur
utilisent ces réglages
† Pour une application java il faut préciser les
propriétés: socksProxyHo socksProxyPor
(SOCKS proxy server), [Link],
[Link], [Link],
[Link], [Link],
[Link], ftpProxySet,
ftpProxyHost, ftpProxyPort,
gopherProxySet, gopherProxyHost,
gopherProxyPort (pour les autres protocoles).
† Pour cela:
java -DsocksProxyHost= [Link] -
DsocksProxyPort= 1080 MyClass
M2 internet H. Fauconnier 10

5
Client-serveur

M2 internet H. Fauconnier 11

Classes
† [Link] (implements [Link])
† [Link].Inet4Address
„ [Link].Inet6Address

† [Link]

† [Link]
„ [Link]

† [Link]
„ [Link]

† [Link]
„ [Link]

† [Link] (implements [Link])


„ [Link]

M2 internet H. Fauconnier 12

6
Classes
† [Link] (implements [Link])
† [Link].Inet4Address
„ [Link].Inet6Address

† [Link]
†
† [Link]
„ [Link]

† [Link]
„ [Link]

† [Link]
„ [Link]
† [Link] (implements [Link])
„ [Link]

M2 internet H. Fauconnier 13

Classes
† [Link] (implements [Link])
„ [Link].Inet4Address
„ [Link].Inet6Address

† [Link]
† [Link]
„ [Link]

† [Link]
† [Link]

† [Link]
„ [Link]

† [Link] (implements [Link])


„ [Link]

M2 internet H. Fauconnier 14

7
Classes
Channel (lien local)
† [Link]
(implements [Link],
[Link])
„ [Link] (implements
[Link])
† [Link]
„ [Link] (implements
[Link],
[Link],
[Link])
„ [Link] (implements
[Link],
[Link],
[Link])

M2 internet H. Fauconnier 15

Classes
Channel:
† [Link] (implements
[Link],
[Link])
„ [Link] (implements
[Link])
† [Link]
„ [Link] (implements
[Link], [Link],
[Link])
„ [Link]
„ [Link] (implements
[Link], [Link],
[Link])
†

M2 internet H. Fauconnier 16

8
II) Adresses internet
† Classe InetAddress:
† Ontenir une InetAddress:
„ En utilisant le DNS)
† public static InetAddress getByName(String
hostName) throws UnknownHostException
† public static InetAddress[] getAllByName(String
hostName) throws UnknownHostException
† public static InetAddress getLocalHost( ) throws
UnknownHostException
„ Sans DNS
† public static InetAddress getByAddress(byte[]
address) throws UnknownHostException
† public static InetAddress getByAddress(String
hostName, byte[] address) throws
UnknownHostException

M2 internet H. Fauconnier 17

Exemples
import [Link].*;
/...
public static void main (String[] args){
try {
InetAddress adresse =
[Link]("[Link]");
[Link](adresse);
} catch (UnknownHostException ex) {
[Link]("[Link] ??");
}

M2 internet H. Fauconnier 18

9
Exemples
public static void main (String[] args){
try {
InetAddress ad =
[Link]("[Link]");
[Link](ad);
} catch (UnknownHostException ex) {
[Link](« [Link] ??");
}
}

M2 internet H. Fauconnier 19

Toutes les adresses…


public static void AllAdresses(String st) {
try {
InetAddress[] addresses =
[Link](st);
for (int i = 0; i < [Link]; i++) {
[Link](addresses[i]);
}
} catch (UnknownHostException ex) {
[Link](st+"est inconnu");
}
}

M2 internet H. Fauconnier 20

10
Mon adresse
public static String MonAdresse() {

try {
InetAddress moi =
[Link]();
return( [Link]());
} catch (UnknownHostException ex) {
return("Mon adresse est inconnue");
}

M2 internet H. Fauconnier 21

InetAddress méthodes…
public String getHostName( )
public byte[] getAddress( )
public String getHostAddress( )
Exemple:
public static void main (String[] args) {
try {
InetAddress ia= [Link]("[Link]");
[Link]([Link]( ));
} catch (Exception ex)
{ [Link](ex); }
}

M2 internet H. Fauconnier 22

11
Divers…
† public boolean isAnyLocalAddress( )
« wildcard »?
† public boolean isLoopbackAddress( )
† public boolean isMulticastAddress( )
† Java 1.5
„ public boolean isReachable(int timeout) throws
IOException
„ public boolean isReachable(NetworkInterface
interface, int ttl, int timeout) throws IOException
„ IPV4 et IPV6:
† public final class Inet4Address extends
InetAddress
† public final class Inet6Address extends
InetAddress

M2 internet H. Fauconnier 23

NetworkInterface
† Exemple:
try {
NetworkInterface ni =
[Link]("eth0");
if (ni == null) {
[Link](" pas de: eth0" );
}
} catch (SocketException ex) { }

M2 internet H. Fauconnier 24

12
Exemple
public static String lookup(String host) {
InetAddress node;
// récupérer l'adresse par getByName
try {
node = [Link](host);
} catch (UnknownHostException ex) {
return "hôte inconnu " + host;
}
if (isHostname(host)) {
return [Link]();
} else {
return [Link]();
}
}
M2 internet H. Fauconnier 25

II) sockets (client)

13
Note
† Dans ce chapitre et le suivant on
s’intéresse aux sockets TCP, on verra
les sockets UDP plus tard.

M2 internet H. Fauconnier 27

Généralités
† Une connexion:
„ (IP adresse+port, IP adresse +port)
„ On peut lire et écrire sur la socket
† Serveur:
„ Associer une socket à une adresse connue (IP+port)
„ Ecoute sur la socket
„ Quand une connexion arrive accept : une nouvelle socket est créée
(nouveau port)
† Rendre le service envoyer/recevoir
„ (en général dans une thread)
† Continuer à écouter
† Client:
„ Crée une socket
„ Demande connexion sur adresse +port du serveur
„ Connexion
„ Envoyer/recevoir
„ Fin de la connexion

M2 internet H. Fauconnier 28

14
Socket en Java
† Serveur
„ Classe SocketServer
† (bind (mais en général par constructeur)
† listen)
† Accept
† getInputStream, getOutputStream
† close

† Client
„ Classe Socket
† (bind)
† connect (mais en général par constructeur)
† getInputStream, getOutputStream
† close

M2 internet H. Fauconnier 29

Attention!
† L’accès aux ports est souvent restreint
† Des firewall peuvent empêcher les
connexions
† Il faut être root pour utiliser des ports
réservés…

M2 internet H. Fauconnier 30

15
Côté client
† Création:
† public Socket(InetAddress address, int port)
throws IOException
† Crée une socket + une connexion avec IP adresse et port
„ En fait:
† Création d’une socket locale attachée à un port + une adresse locale
† Etablissement de la connexion
† IOException en cas d’échec

M2 internet H. Fauconnier 31

Exemple
public static void regarderPortBas(String host) {
for (int i = 1; i < 1024; i++) {
try {
Socket s = new Socket(host, i);
[Link]("Il y a un serveur
sur " + i + " de "+ host);
} catch (UnknownHostException ex) {
[Link](ex);
break;
} catch (IOException ex) {
// exception s'il n'y a pas de serveur
}
}
}
M2 internet H. Fauconnier 32

16
Attention
† Cet exemple peut ne pas bien
fonctionner…
„ Pour des raisons de sécurité certains la
tentative de connexion peut être
bloquante

M2 internet H. Fauconnier 33

Autres constructeurs
try {
InetAddress inward =
[Link]("router");
Socket socket = new Socket("mail", 25, inward, 0);
// work with the sockets...
}
catch (UnknownHostException ex) {
[Link](ex);
}
† Connexion à partir de interface réseau et du port spécifié,
† ‘0’ signifie n’importe quel port

M2 internet H. Fauconnier 34

17
Avec un proxy
SocetAddress proxyAddress = new
InetSocketAddress("[Link]", 1080);
Proxy proxy = new Proxy([Link], proxyAddress)
Socket s = new Socket(proxy);
SocketAddress remote = new
InetSocketAddress("[Link]", 25);
[Link](remote);

M2 internet H. Fauconnier 35

Obtenir des infos…


† public InetAddress getInetAddress( )
† public int getPort( )
† public InetAddress getLocalAddress( )
† public int getLocalPort( )

M2 internet H. Fauconnier 36

18
Exemple
public static void socketInfo(String ... args) {
for (int i = 0; i < [Link]; i++) {
try {
Socket theSocket = new Socket(args[i], 80);
[Link]("Connecté sur " +
[Link]()
+ " port " + [Link]() + " depuis port "
+ [Link]() + " de "
+ [Link]());
}
catch (UnknownHostException ex) {
[Link]("Hôte inconnu " + args[i]);
} catch (SocketException ex) {
[Link]("Connection impossible " + args[i]);
} catch (IOException ex) {
[Link](ex);
}
}
}

M2 internet H. Fauconnier 37

Communiquer…
† public InputStream getInputStream( )
throws IOException
† public OutputStream getOutputStream( )
throws IOException

M2 internet H. Fauconnier 38

19
Exemple: dayTime
public static void time(String ... hlist) {
for (int i=0;i<[Link];i++){
try {
Socket theSocket = new Socket(hlist[i], 13);
InputStream timeStream = [Link]();
StringBuffer time = new StringBuffer();
int c;
while ((c = [Link]()) != -1) [Link]((char) c);
String timeString = [Link]().trim();
[Link]("Il est " + timeString + " à " + hlist[i]);
}
catch (UnknownHostException ex) {
[Link](ex);
} catch (IOException ex) {
[Link](ex);
}
}
}
M2 internet H. Fauconnier 39

Exemple: echo
public static void echo(String hostname, int port) {
PrintWriter out = null;
BufferedReader networkIn = null;
try {
Socket theSocket = new Socket(hostname, port);
networkIn = new BufferedReader(
new InputStreamReader([Link]()));
BufferedReader userIn = new BufferedReader(
new InputStreamReader([Link]));
out = new PrintWriter([Link]());
[Link]("Client: Connecté au serveur d'echo "+ theSocket);
while (true) {
String theLine = [Link]();
[Link](theLine);
[Link]();
if ([Link](".")){[Link](); break;}
[Link]([Link]());
}
}
catch (IOException ex) {[Link](ex);
} finally {
try {
if (networkIn != null) [Link]();
if (out != null) [Link]();
} catch (IOException ex) {}
}
}
}
M2 internet H. Fauconnier 40

20
Echo suite
catch (IOException ex) {
[Link](ex);
} finally {
try {
if (networkIn != null)
[Link]();
if (out != null) [Link]();
} catch (IOException ex) {}

}
M2 internet H. Fauconnier 41

Fermeture
† public void close( ) throws IOException
† Fermeture de la socket:
„ Automatique si une des parties fait un
close
„ garbage collector
„ (le réseau utilise des ressources systèmes
qui sont par définition partagées et
limitées)

M2 internet H. Fauconnier 42

21
Chapitre III
ServerSocket

Principe
1. Création d’un ServerSocket par
constructeur
2. Association (bind) de la socket à une
adresse et un port ((1) et (2) peuvent être
simultanés)
3. Écoute et connexion par accept
1. Communication getInputStream et
getOutputStream
2. close (par le client ou le serveur ou les deux)
4. Aller en (2)
(en général 3 est dans une thread)
M2 internet H. Fauconnier 44

22
Constructeurs
„ public ServerSocket(int port) throws
BindException, IOException
„ public ServerSocket(int port, int
queueLength) throws BindException, IOException
„ public ServerSocket(int port, int queueLength,
InetAddress bindAddress) throws IOException
† Ces constructeurs associe un port et une adresse au
ServerSocket l’usage du port est exclusif et si le
port est déjà occupé une exception est lancée
„ public ServerSocket( ) throws IOException //
Java 1.4

M2 internet H. Fauconnier 45

Exemple
public static void portsLibres() {
for (int port = 1; port <= 65535; port++) {
try {
// exception si le port est utilisé
ServerSocket server = new
ServerSocket(port);
} catch (IOException ex) {
[Link]("serveur sur port"
+ port );
}
}
}

M2 internet H. Fauconnier 46

23
Remarques
† port 0: choisi par le système
† on peut donner une taille sur la file des
connexions en attente
† on peut choisir une adresse particulière sur
la machine locale
† En java >1.4 on peut faire un "bind" explicite:
† public void bind(SocketAddress endpoint)
throws IOException
† public void bind(SocketAddress endpoint,
int queueLength) throws IOException
M2 internet H. Fauconnier 47

Exemple
public static void portQuelconque() {

try {
ServerSocket server = new ServerSocket(0);
[Link]("Le port obtenu est "
+ [Link]());
} catch (IOException ex) {
[Link](ex);
}
}

M2 internet H. Fauconnier 48

24
Connexion accept()
† crée et retourne une nouvelle socket
pour la connexion associée (IP, port)(IP,
port)

M2 internet H. Fauconnier 49

Exemple
ServerSocket server = new
ServerSocket(5776);
while (true) {
Socket connection = [Link]( );
OutputStreamWriter out = new
OutputStreamWriter(
[Link]( ));
[Link]("Connecté:" +connection+"\r\n");
[Link]( );
}
M2 internet H. Fauconnier 50

25
Exemple plus complet
public final static int DEFAULT_PORT = 13;
public static void dayTime(){
dayTime(DEFAULT_PORT);
}
public static void dayTime(int port) {
if (port < 0 || port >= 65536) {
[Link]("Erreur port:");
return;
}
try {
ServerSocket server = new ServerSocket(port);
Socket connection = null;

M2 internet H. Fauconnier 51

Exemple suite
while (true) {
try {
connection = [Link]();
Writer out = new OutputStreamWriter(
[Link]());
Date now = new Date();
[Link]([Link]() +"\r\n");
[Link]();
[Link]();
} catch (IOException ex) {} finally {
try {
if (connection != null) [Link]();
} catch (IOException ex) {}
}
}
} catch (IOException ex) {
[Link](ex);
}
}internet
M2 H. Fauconnier 52

26
Fermeture
public void close( ) throws IOException

Ferme le ServerSocket et toutes les


connexions créées par accept sur la
ServerSocket

M2 internet H. Fauconnier 53

Serveur echo
public static void serveurEcho(int port) {
try {
ServerSocket server = new ServerSocket(port,100);
[Link]("Serveur:"+server+" en écoute sur le port: "
+ [Link]()+" est lancé");
while (true) {
Socket connection = [Link]();
[Link]("Serveur connexion avec: "
+ connection);
Thread echo=new EchoThread(connection);
[Link]();
} catch (IOException ex) {
[Link]("le port" + port + " est occupé");
[Link]("On suppose donc que le service estlancé");
}
}

M2 internet H. Fauconnier 54

27
serveur echo: EchoThread
class EchoThread extends Thread {
BufferedReader in;
PrintWriter out;
Socket connection;
public EchoThread(Socket connection) {
try{
[Link]=connection;
InputStream in=[Link]();
OutputStream out=[Link]();
[Link] = new BufferedReader(new
InputStreamReader(in));
[Link] = new PrintWriter(out);
} catch (IOException ex) {
[Link](ex);
}
}
M2 internet H. Fauconnier 55

run
public void run() {
try {
while (true) {
String st;
st = [Link]();
if ([Link]("."))
[Link]();
[Link]();
break;
}
[Link]("Serveur a reçu:"+st+" de "+connection);
[Link](st);
[Link]();
}
} catch (SocketException ex) { [Link]();
} catch (IOException ex) { [Link](ex);
}
try {
[Link]();
[Link]();
} catch (IOException ex) { [Link]();}
}
}

M2 internet H. Fauconnier 56

28
Remarques
† utilisation des threads pour traiter le
service et éviter de faire attendre les
clients
† on peut aussi utiliser des
entrées/sorties non bloquantes

M2 internet H. Fauconnier 57

Autres méthodes
† public InetAddress getInetAddress( )
† public int getLocalPort( )

M2 internet H. Fauconnier 58

29
Options
† SO_TIMEOUT
† SO_REUSEADDR
† SO_RCVBUF
† public void setPerformancePreferences(int
connectionTime, int latency, int
bandwidth

M2 internet H. Fauconnier 59

IV) Socket UDP

30
UDP

M2 internet H. Fauconnier 61

DatagramPacket
† Un paquet contient au plus 65,507 bytes
† Pour construire les paquet
„ public DatagramPacket(byte[] buffer, int length)
„ public DatagramPacket(byte[] buffer, int offset, int length)
† Pour construire et envoyer
„ public DatagramPacket(byte[] data, int length,
InetAddress destination, int port)
„ public DatagramPacket(byte[] data, int offset, int
length, InetAddress destination, int port) // Java
1.2
„ public DatagramPacket(byte[] data, int length,
SocketAddress destination, int port) // Java 1.4
„ public DatagramPacket(byte[] data, int offset, int
length, SocketAddress destination, int port) //
Java 1.4

M2 internet H. Fauconnier 62

31
Exemple
String s = "On essaie…";
byte[] data = [Link]("ASCII");

try {
InetAddress ia =
[Link]("[Link]");
int port = 7;// existe-t-il?
DatagramPacket dp = new DatagramPacket(data,
[Link], ia, port);
// envoi
}
catch (IOException ex)
}

M2 internet H. Fauconnier 63

Méthodes
† Adresses
„ public InetAddress getAddress( )
„ public int getPort( )
„ public SocketAddress
getSocketAddress( )
„ public void setAddress(InetAddress
remote)
„ public void setPort(int port)
„ public void setAddress(SocketAddress
remote)
M2 internet H. Fauconnier 64

32
Méthodes (suite)
† Manipulation des données:
„ public byte[] getData( )
„ public int getLength( )
„ public int getOffset( )
„ public void setData(byte[] data)
„ public void setData(byte[] data,
int offset, int length )
„ public void setLength(int length)
M2 internet H. Fauconnier 65

Exemple
import [Link].*;
public class DatagramExample {
public static void main(String[] args) {
String s = "Essayons.";
byte[] data = [Link]( );
try {
InetAddress ia = [Link]("[Link]");
int port =7;
DatagramPacket dp = new DatagramPacket(data, [Link], ia, port);
[Link](" Un packet pour" + [Link]( ) + " poirt " +
[Link]( ));
[Link]("il y a " + [Link]( ) + " bytes dans le
packet");
[Link](
new String([Link]( ), [Link]( ), [Link]( )));
}
catch (UnknownHostException e) {
[Link](e);
}
}
}
M2 internet H. Fauconnier 66

33
DatagramSocket
† Constructeurs
„ public DatagramSocket( ) throws
SocketException
„ public DatagramSocket(int port) throws
SocketException
„ public DatagramSocket(int port, InetAddress
interface) throws SocketException
„ public DatagramSocket(SocketAddress interface)
throws SocketException
„ (protected DatagramSocket(DatagramSocketImpl
impl) throws SocketException)

M2 internet H. Fauconnier 67

Exemple
[Link].*;
public class UDPPortScanner {
public static void main(String[] args) {

for (int port = 1024; port <= 65535; port++) {


try {
// exception si utilisé
DatagramSocket server = new DatagramSocket(port);
[Link]( );
}
catch (SocketException ex) {
[Link]("Port occupé" + port + ".");
} // end try
} // end for
}
}

M2 internet H. Fauconnier 68

34
Envoyer et recevoir
† public void send(DatagramPacket dp)
throws IOException
† public void receive(DatagramPacket dp)
throws IOException

M2 internet H. Fauconnier 69

Un exemple: Echo
† UDPServeur
„ UDPEchoServeur
† UDPEchoClient
† SenderThread
† ReceiverThread

M2 internet H. Fauconnier 70

35
Echo: UDPServeur
import [Link].*;
import [Link].*;
public abstract class UDPServeur extends Thread {
private int bufferSize;
protected DatagramSocket sock;
public UDPServeur(int port, int bufferSize)
throws SocketException {
[Link] = bufferSize;
[Link] = new DatagramSocket(port);
}
public UDPServeur(int port) throws SocketException {
this(port, 8192);
}
public void run() {
byte[] buffer = new byte[bufferSize];
while (true) {
DatagramPacket incoming = new DatagramPacket(buffer, [Link]);
try {
[Link](incoming);
[Link](incoming);
}
catch (IOException e) {
[Link](e);
}
} // end while
}
public abstract void respond(DatagramPacket request);
}

M2 internet H. Fauconnier 71

UDPEchoServeur
public class UDPEchoServeur extends UDPServeur {
public final static int DEFAULT_PORT = 2222;
public UDPEchoServeur() throws SocketException {
super(DEFAULT_PORT);
}
public void respond(DatagramPacket packet) {
try {
byte[] data = new byte[[Link]()];
[Link]([Link](), 0, data, 0, [Link]());
try {
String s = new String(data, "8859_1");
[Link]([Link]() + " port "
+ [Link]() + " reçu " + s);
} catch ([Link] ex) {}
DatagramPacket outgoing = new DatagramPacket([Link](),
[Link](), [Link](), [Link]());
[Link](outgoing);
} catch (IOException ex) {
[Link](ex);
}
}
}

M2 internet H. Fauconnier 72

36
Client: UDPEchoClient
public class UDPEchoClient {
public static void lancer(String hostname, int port) {
try {
InetAddress ia = [Link](hostname);
SenderThread sender = new SenderThread(ia, port);
[Link]();
Thread receiver = new ReceiverThread([Link]());
[Link]();
}
catch (UnknownHostException ex) {
[Link](ex);
}
catch (SocketException ex) {
[Link](ex);
}

} // end lancer
}

M2 internet H. Fauconnier 73

ReceiverThread
class ReceiverThread extends Thread {
DatagramSocket socket;
private boolean stopped = false;
public ReceiverThread(DatagramSocket ds) throws SocketException {
[Link] = ds;
}
public void halt() {
[Link] = true;
}
public DatagramSocket getSocket(){
return socket;
}
public void run() {
byte[] buffer = new byte[65507];
while (true) {
if (stopped) return;
DatagramPacket dp = new DatagramPacket(buffer, [Link]);
try {
[Link](dp);
String s = new String([Link](), 0, [Link]());
[Link](s);
[Link]();
} catch (IOException ex) {[Link](ex); }
}
}
M2 internet H. Fauconnier 74
}

37
SenderThread
public class SenderThread extends Thread {
private InetAddress server;
private DatagramSocket socket;
private boolean stopped = false;
private int port;
public SenderThread(InetAddress address, int port)
throws SocketException {
[Link] = address;
[Link] = port;
[Link] = new DatagramSocket();
[Link](server, port);
}
public void halt() {
[Link] = true;
}
//…

M2 internet H. Fauconnier 75

SenderThread
//…
public DatagramSocket getSocket() {
return [Link];
}
public void run() {

try {
BufferedReader userInput = new BufferedReader(new
InputStreamReader([Link]));
while (true) {
if (stopped) return;
String theLine = [Link]();
if ([Link](".")) break;
byte[] data = [Link]();
DatagramPacket output
= new DatagramPacket(data, [Link], server, port);
[Link](output);
[Link]();
}
} // end try
catch (IOException ex) {[Link](ex); }
} // end run
}

M2 internet H. Fauconnier 76

38
Autres méthodes
† public void close( )
† public int getLocalPort( )
† public InetAddress getLocalAddress( )
† public SocketAddress getLocalSocketAddress( )
† public void connect(InetAddress host, int port)
† public void disconnect( )
† public void disconnect( )
† public int getPort( )
† public InetAddress getInetAddress( )
† public InetAddress getRemoteSocketAddress( )

M2 internet H. Fauconnier 77

Options
† SO_TIMEOUT
„ public synchronized void setSoTimeout(int timeout) throws
SocketException
„ public synchronized int getSoTimeout( ) throws IOException
† SO_RCVBUF
„ public void setReceiveBufferSize(int size) throws SocketException
„ public int getReceiveBufferSize( ) throws SocketException
† SO_SNDBUF
„ public void setSendBufferSize(int size) throws SocketException
„ int getSendBufferSize( ) throws SocketException
† SO_REUSEADDR (plusieurs sockets sur la même adresse)
„ public void setReuseAddress(boolean on) throws SocketException
„ boolean getReuseAddress( ) throws SocketException
† SO_BROADCAST
„ public void setBroadcast(boolean on) throws SocketException
„ public boolean getBroadcast( ) throws SocketException

M2 internet H. Fauconnier 78

39

Vous aimerez peut-être aussi